Skip to content

feat(ops): surface fetch errors in UI and log file (closes #95) - #103

Merged
unhappychoice merged 2 commits into
mainfrom
feat/surface-fetch-errors
Apr 24, 2026
Merged

unhappychoice merged 2 commits into
mainfrom
feat/surface-fetch-errors

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

Resolves #95. Fetch failures used to be silent — runtime.rs's .ok()?.ok()? dropped both FetchError::Failed and deadline timeouts on the floor, so a failing widget stayed blank until its TTL rolled over and nothing was logged anywhere.

  • Runtime lift: fetch_all now turns Err(FetchError) into a ⚠ <msg> placeholder and tokio::time::Elapsed into a ⏱ timed out placeholder. Both paths tracing::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.
  • tracing wiring: tracing-subscriber + 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.
  • CacheEntry.kind: new CacheEntryKind { Ok, Err, Timeout }. #[serde(default)] keeps back-compat — legacy cache files without the field deserialize as Ok.
  • Fetcher cleanup: every cached fetcher's Ok(placeholder(...)) bail-out becomes return Err(FetchError::Failed(...)). Per-fetcher placeholder() helpers in github/common.rs, weather.rs, github/avatar.rs, and github/repo.rs are gone, replaced by the one fetcher::error_placeholder + timeout_placeholder pair. 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_err cache + renderer-side compositor), panic-hook capture, remote telemetry, the splashboard logs subcommand, and the docs-site "Debugging" cookbook page.

Test plan

  • cargo test — 492 unit + 12 bin tests pass
  • cargo clippy --all-targets -- -D warnings
  • cargo fmt --all -- --check
  • New tests cover: CacheEntryKind legacy deserialize, runtime lifts Err → placeholder + CacheEntryKind::Err cache write, runtime lifts timeout → placeholder + CacheEntryKind::Timeout cache write, log appender writes a file

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added global logging system with environment-based configuration
    • Improved error propagation across all fetcher operations
  • Bug Fixes

    • Fetchers now properly report errors instead of rendering placeholder content
    • Error and timeout responses are cached with shorter expiration times for faster recovery

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]>
@coderabbitai

coderabbitai Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR implements comprehensive error handling and logging infrastructure for fetch failures. It adds tracing-based logging with file persistence, introduces a CacheEntryKind discriminator to tag cache entries as success/error/timeout, refactors the runtime to explicitly handle fetch failures and timeouts by storing visible placeholder payloads in the cache, and unifies error propagation across all GitHub and weather fetchers instead of silently dropping errors.

Changes

Cohort / File(s) Summary
Logging Infrastructure
Cargo.toml, src/logging.rs, src/lib.rs, src/main.rs
Adds tracing, tracing-subscriber, and tracing-appender dependencies; implements environment-controlled logging initialization with daily file rotation to $HOME/.splashboard/logs/ and idempotent setup via OnceLock; exports logging module and calls init() at CLI startup.
Cache Enhancement
src/cache.rs
Introduces CacheEntryKind enum (Ok, Err, Timeout); adds kind field to CacheEntry with backward-compatible deserialization; adds new_with_kind() constructor for explicit kind specification; updates existing tests to include kind field.
Path Configuration
src/paths.rs
Adds logs_dir() function returning $HOME/.splashboard/logs path; updates environment override test to include new path assertion.
Runtime Error Handling
src/runtime.rs
Refactors fetch_all() to explicitly handle fetch outcomes: successful fetches → CacheEntryKind::Ok, failures → error placeholder + CacheEntryKind::Err, timeouts → timeout placeholder + CacheEntryKind::Timeout; uses shorter TTL (ERROR_CACHE_TTL_SECS) for error/timeout entries; switches cache writes to new_with_kind(); adds regression tests for error and timeout paths.
Public Fetcher Helpers
src/fetcher/mod.rs
Adds error_placeholder() and timeout_placeholder() functions to unify error/timeout payload generation across all fetchers.
GitHub Fetcher Unification
src/fetcher/github/action_history.rs, action_status.rs, assigned_issues.rs, avatar.rs, contributions.rs, contributors_monthly.rs, good_first_issues.rs, languages.rs, my_prs.rs, notifications.rs, recent_releases.rs, repo.rs, repo_issues.rs, repo_prs.rs, repo_stars.rs, review_requests.rs, user.rs
Converts error handling across all GitHub fetchers from returning Ok(placeholder(...)) to propagating Err(FetchError::Failed(...)) for option parsing and repo resolution failures; removes per-fetcher placeholder imports and usage.
Placeholder Function Cleanup
src/fetcher/github/common.rs
Removes shared placeholder() helper function; per-fetcher placeholders are now centralized in src/fetcher/mod.rs.
Weather Fetcher Unification
src/fetcher/weather.rs
Converts option parsing failures from returning Ok(placeholder(...)) to propagating Err(FetchError::Failed(...)); removes placeholder function and imports.
Documentation Refinement
src/fetcher/github/client.rs
Clarifies rest_get() doc comment to note that non-2xx errors with JSON message are actionable both in runtime placeholders and log output.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 Hop! Hop! No more silent screams,
Our errors now shine with visible beams,
Cache-tagged and logged for all to see,
Each failed fetch finds destiny.
From placeholder placeholders to truthful displays,
We've tamed the darkness of debugging days! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.56% 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 accurately describes the main objective: surfacing fetch errors in both UI and log file, closing issue #95.
Linked Issues check ✅ Passed The PR comprehensively implements all primary coding objectives from issue #95: logging infrastructure with tracing, CacheEntry.kind field, error/timeout placeholders, unified error propagation, and cache writes with short TTL.
Out of Scope Changes check ✅ Passed All changes directly support the issue #95 objectives. Dependencies added (tracing/tracing-appender) and logging module are on-scope; cache schema changes (kind field) support error tracking; runtime/fetcher changes implement the unified error surface; no unrelated modifications detected.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/surface-fetch-errors

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.

@codecov

codecov Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.19324% with 41 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.73%. Comparing base (ee948df) to head (01692c7).
⚠️ Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
src/logging.rs 55.35% 25 Missing ⚠️
src/runtime.rs 85.29% 15 Missing ⚠️
src/main.rs 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Files with missing lines Coverage Δ
src/cache.rs 97.25% <100.00%> (+0.28%) ⬆️
src/fetcher/github/action_history.rs 12.50% <ø> (ø)
src/fetcher/github/action_status.rs 41.97% <ø> (ø)
src/fetcher/github/assigned_issues.rs 24.32% <ø> (ø)
src/fetcher/github/avatar.rs 58.68% <ø> (+1.70%) ⬆️
src/fetcher/github/client.rs 37.93% <ø> (ø)
src/fetcher/github/common.rs 52.38% <ø> (+3.12%) ⬆️
src/fetcher/github/contributions.rs 63.88% <ø> (ø)
src/fetcher/github/contributors_monthly.rs 9.57% <ø> (ø)
src/fetcher/github/good_first_issues.rs 17.64% <ø> (ø)
... and 16 more

... and 8 files with indirect coverage changes

🚀 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.

…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]>

@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: 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 | 🟡 Minor

Error TTL can exceed a widget's configured refresh_interval.

ERROR_CACHE_TTL_SECS = 30 is applied unconditionally on the Err/Timeout arms, but ttl on the Ok arm comes from w.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 — because should_refresh reads 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 after Cli::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: collapse StatsOutcome now that Computing is always re-raised as Err.

With this change, the Computing variant is constructed in fetch_stats only to be immediately converted to FetchError::Failed here. You can fold the mapping into fetch_stats and 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, return Err(FetchError::Failed("github: stats warming up (refresh in a minute)".into())) for the 202 branch, dropping the StatsOutcome enum entirely.

As per coding guidelines: "Keep functions small with single responsibility (~10–15 lines)" — this also trims fetch slightly.

🤖 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: concurrent init() calls can waste a background worker.

Two threads racing into init() can both pass the GUARD.get().is_some() check and each construct an appender + tracing_appender::non_blocking(...) worker thread. The loser's try_init() and GUARD.set() both fail, and its guard is 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 &PathBuf to &Path to align with clippy's ptr_arg lint.

The parameter type &PathBuf forces callers to own the allocation unnecessarily; &Path accepts both &PathBuf and &Path via AsRef<Path>. The Builder::build method 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 &PathBuf directly, 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 mirror shape_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_placeholder interpolates the raw msg without truncation or newline scrubbing. A FetchError::Failed whose message contains a newline or runs long will break the "one-line reason" contract from issue #95 and 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

📥 Commits

Reviewing files that changed from the base of the PR and between ee948df and 01692c7.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (28)
  • Cargo.toml
  • src/cache.rs
  • src/fetcher/github/action_history.rs
  • src/fetcher/github/action_status.rs
  • src/fetcher/github/assigned_issues.rs
  • src/fetcher/github/avatar.rs
  • src/fetcher/github/client.rs
  • src/fetcher/github/common.rs
  • src/fetcher/github/contributions.rs
  • src/fetcher/github/contributors_monthly.rs
  • src/fetcher/github/good_first_issues.rs
  • src/fetcher/github/languages.rs
  • src/fetcher/github/my_prs.rs
  • src/fetcher/github/notifications.rs
  • src/fetcher/github/recent_releases.rs
  • src/fetcher/github/repo.rs
  • src/fetcher/github/repo_issues.rs
  • src/fetcher/github/repo_prs.rs
  • src/fetcher/github/repo_stars.rs
  • src/fetcher/github/review_requests.rs
  • src/fetcher/github/user.rs
  • src/fetcher/mod.rs
  • src/fetcher/weather.rs
  • src/lib.rs
  • src/logging.rs
  • src/main.rs
  • src/paths.rs
  • src/runtime.rs
💤 Files with no reviewable changes (1)
  • src/fetcher/github/common.rs

Comment on lines 89 to 97
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(),
)),

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

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.

@unhappychoice
unhappychoice merged commit a9dcbb1 into main Apr 24, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the feat/surface-fetch-errors branch April 24, 2026 18:13
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.

ops: surface fetch errors in UI + log file (no more silent failures)

1 participant