Skip to content

feat(runtime): async fetch + on-disk cache layer (#4) - #28

Merged
unhappychoice merged 4 commits into
mainfrom
feat/4-async-cache
Apr 21, 2026
Merged

unhappychoice merged 4 commits into
mainfrom
feat/4-async-cache

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Fetcher trait with Safety (Safe / Network / Exec) + Registry. Classification is the hook core: Trust model for per-directory config (direnv-style) #27's trust layer will gate on later.
  • On-disk Cache at ~/.cache/splashboard/<widget-id>.json; entries carry refreshed_at + ttl_seconds, written via atomic rename, skipped on refresh when still fresh.
  • runtime::run() orchestrates cache-first rendering: load entries → draw immediately if anything cached → tokio::JoinSet fetches only stale widgets with a per-task deadline → redraw if changed → persist.
  • --wait / general.wait_for_fresh opts into a one-fresh-frame path (skips the cached draw, waits up to the longer deadline).
  • main.rs becomes #[tokio::main]; old stubs.rs is folded into fetcher/stub.rs so stubs live behind the fetcher trait and can be replaced one by one in widget: Clock / date / greeting #7-10.

Test plan

  • cargo fmt --check
  • cargo clippy --all-targets -- -D warnings
  • cargo test (83 passed, incl. cache tempdir round-trip, runtime fetch + skip, stub coverage)
  • Manual: run splashboard twice and confirm second invocation reads cache within the TTL; confirm --wait waits for fresh frame.

Closes #4.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added local widget caching with configurable time-to-live to reduce data fetches.
    • Added --wait CLI flag to force fetching fresh data instead of using cached values.
    • Implemented pluggable fetcher system for flexible widget data sources.
  • Chores

    • Migrated to async multi-threaded runtime for improved performance and responsiveness.
    • Updated default greeting widget with format configuration option.

Introduce a small runtime that loads cached payloads synchronously,
renders immediately with whatever is on disk, kicks off per-widget
fetches on a tokio multi-thread runtime, and redraws (and persists)
when fresh data lands. Per-task timeouts cap the wait so the
shell-startup path never blocks noticeably.

- Fetcher trait with Safety classification (Safe / Network / Exec)
  so the trust layer (#27) can gate on it without re-plumbing.
- Registry of built-in fetchers. All six are still stubs today;
  real implementations land in #7-10.
- CacheEntry = {refreshed_at, ttl_seconds, payload} written per
  widget id under the user cache dir with an atomic rename. TTL
  drives the skip-refetch decision so widgets with long
  refresh_interval stay cheap across invocations.
- --wait / general.wait_for_fresh opts into the fetch-then-draw
  flow for callers that prefer one fresh frame over one fast frame.
@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

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

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 40 minutes and 58 seconds.

⌛ How to resolve this issue?

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

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

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

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

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d16bf5d3-8993-4a90-a281-bb9127596ca5

📥 Commits

Reviewing files that changed from the base of the PR and between 160f2dd and aa6e7a2.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • Cargo.toml
  • src/cache.rs
  • src/fetcher/mod.rs
  • src/runtime.rs
📝 Walkthrough

Walkthrough

Introduces an async Tokio-based runtime with pluggable fetcher abstraction and on-disk JSON caching. New modules implement cache persistence, fetcher trait with built-in stubs, and concurrent refresh orchestration. Converts main.rs to async, adds --wait CLI flag, and removes synchronous stub module.

Changes

Cohort / File(s) Summary
Async Runtime Foundation
Cargo.toml, src/main.rs
Added tokio (multi-threaded) and async-trait dependencies; converted main to async Tokio entrypoint with #[tokio::main], introduced --wait flag, and delegated rendering to new runtime::run() for cache-aware refresh orchestration.
Cache Layer
src/cache.rs
New on-disk JSON caching module with CacheEntry (payload + TTL metadata) and Cache (load/store/sanitize operations); supports atomic writes via temp files and freshness checks based on unix timestamps.
Fetcher Abstraction
src/fetcher/mod.rs, src/fetcher/stub.rs
Introduced pluggable Fetcher trait with Registry for dynamic registration; implemented six built-in stub fetchers (StaticText, ClockStub, DiskStub, GitCommitsStub, SystemStub, GithubPrsStub) returning hardcoded payloads with varying safety levels.
Fetch & Render Orchestration
src/runtime.rs
New async module orchestrating cache loads, concurrent fetches via tokio::JoinSet, timeout-driven refresh decisions, cache persistence, and conditional redraws; supports fast cache-first startup and --wait mode for fresh-data blocking.
Configuration & Cleanup
src/default_config.toml, src/stubs.rs
Updated greeting widget config with format field; deleted synchronous stubs.rs module, replacing its widgets_for() function with fetcher-driven payload generation in runtime.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as CLI / main.rs
    participant Cache as Cache Module
    participant Registry as Fetcher Registry
    participant Fetchers as Built-in Fetchers
    participant IO as Terminal / File I/O
    
    CLI->>Cache: load all cached entries
    Cache-->>CLI: returns HashMap<WidgetId, Payload>
    
    alt not waiting & cache hit
        CLI->>IO: render cached payloads immediately
        IO-->>CLI: ✓ fast startup (~50ms)
    end
    
    CLI->>Registry: resolve fetchers for widgets
    Registry-->>CLI: returns Arc<dyn Fetcher> per widget
    
    par concurrent fetch with timeout
        loop for each non-fresh widget
            CLI->>Fetchers: fetch(FetchContext)
            Fetchers-->>CLI: Result<Payload, FetchError>
        end
    end
    
    loop for each fetched widget
        CLI->>Cache: store(widget_id, CacheEntry)
        Cache->>IO: write .json atomically
        IO-->>Cache: ✓
    end
    
    alt wait=true OR no prior cache
        CLI->>IO: render fresh payloads
    end
    
    IO-->>CLI: ✓ exit
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~105 minutes

Poem

🐰 Hopping through time with async and grace,
We cache our results in the fastest of pace,
Refresh while we wait, or dash right away,
Fresh data by dawn, or stale data's okay!
The fetcher abstraction hops plugin by plugin,
This fluffy new runtime won't leave us spinnin'! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(runtime): async fetch + on-disk cache layer (#4)' clearly and concisely summarizes the main changes: async fetching and on-disk caching functionality.
Linked Issues check ✅ Passed All coding requirements from issue #4 are met: Fetcher trait with Safety classification, on-disk cache layer, runtime::run() with cache-first rendering, --wait option, async tokio main, and comprehensive test coverage.
Out of Scope Changes check ✅ Passed All changes are directly aligned with issue #4 objectives: cache implementation, fetcher trait/registry, runtime async pipeline, and supporting refactors (main.rs, stubs consolidation) are all in scope.

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

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

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.

@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: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Cargo.toml`:
- Line 24: The Cargo.toml allows tokio = "1" but the code uses
tokio::task::JoinSet (stabilized in tokio 1.21.0); update the tokio dependency
constraint in Cargo.toml to require at least 1.21.0 (e.g., bump the version
specifier to a constraint with a lower bound of 1.21.0) and keep the existing
features ("rt-multi-thread", "macros", "time"); then run cargo build/tests to
verify JoinSet resolves correctly.

In `@src/cache.rs`:
- Around line 26-28: The current is_fresh() uses age_of(self.refreshed_at) with
saturating_sub which makes future-dated refreshed_at appear age 0; instead
explicitly check refreshed_at against now and treat future timestamps as stale:
in is_fresh(), compute now (the same way age_of uses), return false immediately
if self.refreshed_at > now, otherwise compute age and compare to ttl_seconds.
Apply the same pattern to the other freshness check referenced around lines
92-94 (use the same explicit future-timestamp guard before comparing age to
ttl_seconds) so any clock-skew or tampered future timestamps are considered
stale.
- Around line 61-76: The current sanitize function in path_for (used by
PathBuf::join in path_for) is lossy and causes collisions (e.g. "a/b" -> "a_b");
replace sanitize with a collision-resistant, filesystem-safe encoder such as
either (a) URL-safe percent-encoding or base64url of the full widget_id, or (b)
a short hex hash (e.g. SHA-256/SHA-1) optionally prefixed by a sanitized
human-readable fragment; update the sanitize function name or its caller in
path_for to use that encoder so filenames are deterministic, unique per
widget_id, and contain only safe characters while preserving the .json
extension. Ensure decoding is not required (store only encoded filename) and
keep the API of path_for unchanged.

In `@src/runtime.rs`:
- Around line 40-47: The CLI `--wait` path currently reuses still-fresh cache
because fetch_all applies should_refresh; change the logic so `--wait` forces
refresh by adding a force refresh flag to fetch_all (or an override parameter)
and propagate it through calls that compute freshness (e.g., should_refresh) so
cached entries are not treated as fresh when the CLI flag is present; update the
call sites that set `fresh = fetch_all(&registry, cache.as_ref(),
&config.widgets, &entries, deadline).await` (and the analogous call further
down) to pass the force-refresh flag when `--wait` is active and ensure
should_refresh consults that flag.
- Around line 71-75: entries_to_payloads currently drops cache metadata so stale
items render as fresh; update it to preserve and mark staleness on the payloads
by copying the cache-entry's staleness flag into the Payload before returning.
Locate entries_to_payloads and, for each (k, v), set the payload's staleness
indicator (e.g., Payload.is_stale or payload.metadata.stale) from CacheEntry
(e.g., CacheEntry.is_stale or CacheEntry.metadata) rather than returning
v.payload.clone() unchanged; if Payload lacks a staleness field, add one and
populate it here so downstream rendering can show the stale indicator.
- Around line 34-37: The initial draw is skipped when payloads are empty
(drew_cached = !wait && !payloads.is_empty()), causing a blank wait before
fetch_all completes; change the logic in runtime.rs so that you always perform
an initial draw call (invoke draw(&mut terminal, &layout, &payloads) or draw a
default/empty frame when payloads.is_empty()) instead of only when drew_cached
is true, and then adjust the subsequent redraw condition that currently relies
on drew_cached (and any checks around fetch_all) to avoid double-drawing —
ensure the variable drew_cached remains available for later redraw decisions but
not for deciding whether to render the first frame.
🪄 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: 9e16f513-633c-4c29-bbff-c0acdf7e5565

📥 Commits

Reviewing files that changed from the base of the PR and between ea3cf0f and 160f2dd.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • Cargo.toml
  • src/cache.rs
  • src/default_config.toml
  • src/fetcher/mod.rs
  • src/fetcher/stub.rs
  • src/main.rs
  • src/runtime.rs
  • src/stubs.rs
💤 Files with no reviewable changes (1)
  • src/stubs.rs

Comment thread Cargo.toml
tui-big-text = "0.7"
ratatui-image = "4"
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] }

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Confirm this PR uses JoinSet.
rg -n -C2 'tokio::task::JoinSet|JoinSet' .

# Inspect the locked Tokio version, if Cargo.lock is present.
if [ -f Cargo.lock ]; then
  awk '
    $0 == "[[package]]" { in_pkg=0 }
    $0 == "name = \"tokio\"" { in_pkg=1; print; next }
    in_pkg && /^version = / { print; in_pkg=0 }
  ' Cargo.lock
fi

Repository: unhappychoice/splashboard

Length of output: 568


🌐 Web query:

Which Tokio crate version first included tokio::task::JoinSet?

💡 Result:

The tokio::task::JoinSet was first included in Tokio version 1.18.0 as an unstable feature (requiring the "tokio_unstable" feature flag). It was stabilized in version 1.21.0.

Citations:


Raise Tokio's lower bound to 1.21.0, where JoinSet was stabilized.

The code uses tokio::task::JoinSet but the manifest allows tokio = "1", which resolves to versions before 1.21.0 where JoinSet is unavailable. Update the dependency constraint to prevent compilation failures for downstream consumers.

🛠️ Manifest fix
-tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] }
+tokio = { version = "1.21", features = ["rt-multi-thread", "macros", "time"] }
📝 Committable suggestion

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

Suggested change
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] }
tokio = { version = "1.21", features = ["rt-multi-thread", "macros", "time"] }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Cargo.toml` at line 24, The Cargo.toml allows tokio = "1" but the code uses
tokio::task::JoinSet (stabilized in tokio 1.21.0); update the tokio dependency
constraint in Cargo.toml to require at least 1.21.0 (e.g., bump the version
specifier to a constraint with a lower bound of 1.21.0) and keep the existing
features ("rt-multi-thread", "macros", "time"); then run cargo build/tests to
verify JoinSet resolves correctly.

Comment thread src/cache.rs
Comment on lines +26 to +28
pub fn is_fresh(&self) -> bool {
age_of(self.refreshed_at) < self.ttl_seconds
}

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

Treat future-dated cache entries as stale.

saturating_sub makes a future refreshed_at look like age 0, so clock skew or a tampered cache file can keep stale data fresh indefinitely.

🛠️ Proposed freshness fix
     pub fn is_fresh(&self) -> bool {
-        age_of(self.refreshed_at) < self.ttl_seconds
+        let now = now_secs();
+        self.refreshed_at <= now && now - self.refreshed_at < self.ttl_seconds
     }
 }
-fn age_of(past: u64) -> u64 {
-    now_secs().saturating_sub(past)
-}
-

Also applies to: 92-94

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/cache.rs` around lines 26 - 28, The current is_fresh() uses
age_of(self.refreshed_at) with saturating_sub which makes future-dated
refreshed_at appear age 0; instead explicitly check refreshed_at against now and
treat future timestamps as stale: in is_fresh(), compute now (the same way
age_of uses), return false immediately if self.refreshed_at > now, otherwise
compute age and compare to ttl_seconds. Apply the same pattern to the other
freshness check referenced around lines 92-94 (use the same explicit
future-timestamp guard before comparing age to ttl_seconds) so any clock-skew or
tampered future timestamps are considered stale.

Comment thread src/cache.rs
Comment on lines +61 to +76
pub fn path_for(&self, widget_id: &str) -> PathBuf {
self.dir.join(format!("{}.json", sanitize(widget_id)))
}
}

fn sanitize(s: &str) -> String {
s.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Avoid cache collisions from lossy widget-id sanitization.

sanitize maps many distinct IDs to the same filename, e.g. a/b and a_b both become a_b.json, which can load the wrong widget payload.

🛠️ Proposed collision-resistant encoding
     pub fn path_for(&self, widget_id: &str) -> PathBuf {
-        self.dir.join(format!("{}.json", sanitize(widget_id)))
+        self.dir.join(format!("{}.json", encode_widget_id(widget_id)))
     }
 }
 
-fn sanitize(s: &str) -> String {
-    s.chars()
-        .map(|c| {
-            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
-                c
-            } else {
-                '_'
-            }
-        })
-        .collect()
+fn encode_widget_id(s: &str) -> String {
+    let mut out = String::new();
+    for b in s.bytes() {
+        match b {
+            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' => out.push(char::from(b)),
+            _ => {
+                use std::fmt::Write as _;
+                let _ = write!(out, "~{b:02X}");
+            }
+        }
+    }
+    if out.is_empty() { "_".into() } else { out }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/cache.rs` around lines 61 - 76, The current sanitize function in path_for
(used by PathBuf::join in path_for) is lossy and causes collisions (e.g. "a/b"
-> "a_b"); replace sanitize with a collision-resistant, filesystem-safe encoder
such as either (a) URL-safe percent-encoding or base64url of the full widget_id,
or (b) a short hex hash (e.g. SHA-256/SHA-1) optionally prefixed by a sanitized
human-readable fragment; update the sanitize function name or its caller in
path_for to use that encoder so filenames are deterministic, unique per
widget_id, and contain only safe characters while preserving the .json
extension. Ensure decoding is not required (store only encoded filename) and
keep the API of path_for unchanged.

Comment thread src/runtime.rs
Comment on lines +34 to +37
let drew_cached = !wait && !payloads.is_empty();
if drew_cached {
draw(&mut terminal, &layout, &payloads)?;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Draw an initial default frame even when the cache is empty.

With no cached payloads, the default path skips the immediate draw and waits for fetch_all, so first-run or fully stale startup can block before rendering.

⚡ Proposed fast-path adjustment
-    let drew_cached = !wait && !payloads.is_empty();
-    if drew_cached {
+    let drew_initial = !wait;
+    if drew_initial {
         draw(&mut terminal, &layout, &payloads)?;
     }

Then update the later redraw condition:

-    if !drew_cached || changed {
+    if !drew_initial || changed {
         draw(&mut terminal, &layout, &payloads)?;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/runtime.rs` around lines 34 - 37, The initial draw is skipped when
payloads are empty (drew_cached = !wait && !payloads.is_empty()), causing a
blank wait before fetch_all completes; change the logic in runtime.rs so that
you always perform an initial draw call (invoke draw(&mut terminal, &layout,
&payloads) or draw a default/empty frame when payloads.is_empty()) instead of
only when drew_cached is true, and then adjust the subsequent redraw condition
that currently relies on drew_cached (and any checks around fetch_all) to avoid
double-drawing — ensure the variable drew_cached remains available for later
redraw decisions but not for deciding whether to render the first frame.

Comment thread src/runtime.rs
Comment on lines +40 to +47
let fresh = fetch_all(
&registry,
cache.as_ref(),
&config.widgets,
&entries,
deadline,
)
.await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Make --wait force a refresh instead of reusing fresh cache.

fetch_all always applies should_refresh, so --wait can skip widgets with a still-fresh cache entry and render cached data. That conflicts with the CLI promise to wait for current values.

🛠️ Proposed force-refresh path
     let fresh = fetch_all(
         &registry,
         cache.as_ref(),
         &config.widgets,
         &entries,
         deadline,
+        wait,
     )
     .await;
 async fn fetch_all(
     registry: &Registry,
     cache: Option<&Cache>,
     widgets: &[WidgetConfig],
     cached: &HashMap<WidgetId, CacheEntry>,
     deadline: Duration,
+    force_refresh: bool,
 ) -> HashMap<WidgetId, Payload> {
     let mut set = JoinSet::new();
     for w in widgets {
-        if !should_refresh(cached, w) {
+        if !force_refresh && !should_refresh(cached, w) {
             continue;
         }

Also applies to: 78-88

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/runtime.rs` around lines 40 - 47, The CLI `--wait` path currently reuses
still-fresh cache because fetch_all applies should_refresh; change the logic so
`--wait` forces refresh by adding a force refresh flag to fetch_all (or an
override parameter) and propagate it through calls that compute freshness (e.g.,
should_refresh) so cached entries are not treated as fresh when the CLI flag is
present; update the call sites that set `fresh = fetch_all(&registry,
cache.as_ref(), &config.widgets, &entries, deadline).await` (and the analogous
call further down) to pass the force-refresh flag when `--wait` is active and
ensure should_refresh consults that flag.

Comment thread src/runtime.rs
Comment on lines +71 to +75
fn entries_to_payloads(entries: &HashMap<WidgetId, CacheEntry>) -> HashMap<WidgetId, Payload> {
entries
.iter()
.map(|(k, v)| (k.clone(), v.payload.clone()))
.collect()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Mark stale cached payloads before rendering them.

entries_to_payloads strips cache metadata, so stale cached data is rendered exactly like fresh data until refresh completes. The PR objective calls for stale cache to be shown with an indicator.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/runtime.rs` around lines 71 - 75, entries_to_payloads currently drops
cache metadata so stale items render as fresh; update it to preserve and mark
staleness on the payloads by copying the cache-entry's staleness flag into the
Payload before returning. Locate entries_to_payloads and, for each (k, v), set
the payload's staleness indicator (e.g., Payload.is_stale or
payload.metadata.stale) from CacheEntry (e.g., CacheEntry.is_stale or
CacheEntry.metadata) rather than returning v.payload.clone() unchanged; if
Payload lacks a staleness field, add one and populate it here so downstream
rendering can show the stale indicator.

Widget id is just an instance name; two projects both configuring a
widget called "clock" (or even the same project with two widgets
pointing at different fetcher params) would collide on the single
<cache_dir>/<widget_id>.json file.

Move to fetcher-declared keys instead. `Fetcher::cache_key(ctx)` has
a default of `name + sha256(name|format)[..8]`; repo- or cwd-aware
fetchers can override to mix those in. Upshots:

- Same fetcher + same params shares cache across projects and
  widgets (clock, disk, system — one fetch covers everyone).
- Different params (future: github_prs on different repos) land in
  separate files automatically.
- Keys are also the hook the trust layer (#27) will classify on, so
  we're not re-plumbing a second identity later.
Two shells opening at the same time both land in Cache::store for
the same key. The old `path.with_extension("tmp")` gave both
processes the same tmp path, so one `write` would overwrite the
other's buffer mid-flight before either rename landed — the final
file could end up as whichever partial write happened to stick.

Generate tmp names as `<final>.<pid>.<seq>.tmp` with a process-local
atomic counter. Each store now touches a distinct tmp file; the
atomic rename that follows is last-writer-wins, which is fine.

Adds a 32-thread concurrent store test that also asserts no tmp
files leak into the cache directory.
Two shells opening at the same time both found cache stale and both
fired the same fetcher — e.g. github_prs hits the GitHub API twice
for identical inputs.

Add a non-blocking, create-exclusive lock file per cache key. Fetch
decision becomes: acquire <key>.lock; if held by another process,
skip this widget for this round and render whatever was cached.
Never blocks shell startup.

- `<cache_dir>/<sanitized_key>.lock`, opened with `create_new`. pid
  written inside for debuggability.
- Lock is RAII — dropped after the spawned fetch task finishes,
  which removes the file.
- Locks older than 30s are considered stale and stolen (crashed
  process cleanup).

Deliberate trade-off: the skipping invocation doesn't see fresh
data this round. Next invocation reads the cache the winner just
wrote. This preserves the "never block the shell" invariant.
@unhappychoice
unhappychoice merged commit 3949d8c into main Apr 21, 2026
5 checks passed
@unhappychoice
unhappychoice deleted the feat/4-async-cache branch April 21, 2026 19:50
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.

core: Async fetch + cache layer (lazy loading)

1 participant