Repository navigation
feat(runtime): async fetch + on-disk cache layer (#4) - #28
Conversation
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.
|
Warning Rate limit exceeded
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 We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (4)
📝 WalkthroughWalkthroughIntroduces 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 Changes
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
Estimated code review effort🎯 5 (Critical) | ⏱️ ~105 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
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(®istry, 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
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (8)
Cargo.tomlsrc/cache.rssrc/default_config.tomlsrc/fetcher/mod.rssrc/fetcher/stub.rssrc/main.rssrc/runtime.rssrc/stubs.rs
💤 Files with no reviewable changes (1)
- src/stubs.rs
| 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"] } |
There was a problem hiding this comment.
🧩 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
fiRepository: 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:
- 1: https://docs.rs/tokio/1.18.2/tokio/task/struct.JoinSet.html
- 2: https://github.com/tokio-rs/tokio/releases/tag/tokio-1.21.0
- 3: task: stabilize
JoinSettokio-rs/tokio#4535 - 4: chore: stabilize JoinSet and AbortHandle tokio-rs/tokio#4920
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.
| 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.
| pub fn is_fresh(&self) -> bool { | ||
| age_of(self.refreshed_at) < self.ttl_seconds | ||
| } |
There was a problem hiding this comment.
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.
| 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() | ||
| } |
There was a problem hiding this comment.
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.
| let drew_cached = !wait && !payloads.is_empty(); | ||
| if drew_cached { | ||
| draw(&mut terminal, &layout, &payloads)?; | ||
| } |
There was a problem hiding this comment.
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.
| let fresh = fetch_all( | ||
| ®istry, | ||
| cache.as_ref(), | ||
| &config.widgets, | ||
| &entries, | ||
| deadline, | ||
| ) | ||
| .await; |
There was a problem hiding this comment.
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(
®istry,
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(®istry,
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.
| fn entries_to_payloads(entries: &HashMap<WidgetId, CacheEntry>) -> HashMap<WidgetId, Payload> { | ||
| entries | ||
| .iter() | ||
| .map(|(k, v)| (k.clone(), v.payload.clone())) | ||
| .collect() |
There was a problem hiding this comment.
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.
Summary
Fetchertrait withSafety(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.Cacheat~/.cache/splashboard/<widget-id>.json; entries carryrefreshed_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::JoinSetfetches only stale widgets with a per-task deadline → redraw if changed → persist.--wait/general.wait_for_freshopts into a one-fresh-frame path (skips the cached draw, waits up to the longer deadline).main.rsbecomes#[tokio::main]; oldstubs.rsis folded intofetcher/stub.rsso stubs live behind the fetcher trait and can be replaced one by one in widget: Clock / date / greeting #7-10.Test plan
cargo fmt --checkcargo clippy --all-targets -- -D warningscargo test(83 passed, incl. cache tempdir round-trip, runtime fetch + skip, stub coverage)splashboardtwice and confirm second invocation reads cache within the TTL; confirm--waitwaits for fresh frame.Closes #4.
Summary by CodeRabbit
Release Notes
New Features
--waitCLI flag to force fetching fresh data instead of using cached values.Chores