Repository navigation
feat(fetcher): add nasa_apod — NASA Astronomy Picture of the Day - #230
Conversation
Multi-shape cached fetcher feeding the shipped media_image renderer plus text shapes. `Image` (default) downloads the day's picture; `Text` / `TextBlock` / `MarkdownTextBlock` / `LinkedTextBlock` / `Entries` reshape the same single API read into the title / explanation / date metadata. Safety::Safe — `api.nasa.gov` is hardcoded and the optional `api_key` only leaves to that known host. The JSON response carries an arbitrary image URL string, so its host is re-validated against an allowlist before download (mirrors `random_dog`). On video days the `Image` shape errors out while text shapes still render. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ 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. 📝 WalkthroughWalkthroughThis PR introduces a new NASA Astronomy Picture of the Day (APOD) fetcher that resolves API credentials, fetches APOD metadata and images from the NASA API, validates security constraints (host allowlist, file size caps), caches images with format detection, and supports rendering as image files or formatted text metadata. The fetcher is registered in the built-in fetcher registry. ChangesNASA APOD Fetcher
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 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 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 #230 +/- ##
==========================================
- Coverage 94.59% 94.57% -0.02%
==========================================
Files 194 195 +1
Lines 49657 50240 +583
==========================================
+ Hits 46971 47514 +543
- Misses 2686 2726 +40
🚀 New features to boost your workflow:
|
- fetch_apod now takes the built URL (not the api key) so its success / http-status / invalid-json / malformed-url paths are exercised against a local server instead of re-implemented inline in the test. - Extract text-shape body construction into a pure `text_body` so every Text / TextBlock / MarkdownTextBlock / LinkedTextBlock branch is testable without a network round-trip. - Add fetch_bytes success + malformed-url tests and download_image off-host / cache-dir-failure tests, matching the random_dog sibling. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/fetcher/nasa_apod.rs`:
- Around line 721-735: The test live_downloads_todays_apod currently
unconditionally removes SPLASHBOARD_HOME and can clobber a pre-existing
environment value; before calling unsafe { std::env::set_var("SPLASHBOARD_HOME",
tmp.path()) } capture the prior value with std::env::var_os("SPLASHBOARD_HOME")
into a local (e.g., prev_home), then at the end restore that state: if
prev_home.is_some() call std::env::set_var to restore it, otherwise call
std::env::remove_var, keeping the existing unsafe blocks around env operations
and using the same function names live_downloads_todays_apod, tmp, and
SPLASHBOARD_HOME to locate where to apply the change.
- Around line 253-273: The fetch_bytes function currently calls
Response::bytes() which buffers the entire body before checking MAX_BYTES;
change fetch_bytes to consume response.bytes_stream() and stream-chunk-by-chunk
while tracking a running total, returning Err(FetchError::Failed(...))
immediately if total > MAX_BYTES, and otherwise append chunks into a buffer
(e.g., BytesMut or Vec<u8>) and return the collected bytes; update the code
paths that map transport errors to the same FetchError variants and add the
needed StreamExt import (or iterate with .next()) so the size enforcement
happens during download rather than after buffering.
🪄 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: e404cdc1-343d-4c42-8c95-ef805aeb4cbb
📒 Files selected for processing (2)
src/fetcher/mod.rssrc/fetcher/nasa_apod.rs
| async fn fetch_bytes(url: &str) -> Result<Vec<u8>, FetchError> { | ||
| let res = http() | ||
| .get(url) | ||
| .send() | ||
| .await | ||
| .map_err(|e| FetchError::Failed(format!("apod image request failed: {e}")))?; | ||
| let status = res.status(); | ||
| if !status.is_success() { | ||
| return Err(FetchError::Failed(format!("apod image {status}"))); | ||
| } | ||
| let bytes = res | ||
| .bytes() | ||
| .await | ||
| .map_err(|e| FetchError::Failed(format!("apod image body: {e}")))?; | ||
| if bytes.len() > MAX_BYTES { | ||
| return Err(FetchError::Failed(format!( | ||
| "apod image too large: {} bytes", | ||
| bytes.len() | ||
| ))); | ||
| } | ||
| Ok(bytes.to_vec()) |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
For reqwest 0.12, does Response::bytes()buffer the entire response body before returning? What is the recommendedbytes_stream() pattern to enforce a strict maximum response size during download?
💡 Result:
Yes, in reqwest 0.12, Response::bytes() buffers the entire response body before returning. It uses http_body_util::BodyExt::collect(self.res.into_body()).await.map(|buf| buf.to_bytes()), which aggregates all chunks into a single Bytes object.[1] The recommended pattern for bytes_stream() to enforce a strict maximum response size is to use http_body_util::LengthLimit to wrap the body (requires adding http-body-util dependency), or manually iterate over the stream while tracking total bytes consumed. Official recommendation from reqwest maintainer: use http_body_util::Limited.[2][3][4] Example using LengthLimit (add http-body-util = "0.1" to Cargo.toml): use http_body_util::{LengthLimit, BodyExt}; let stream = response.bytes_stream().map_ok(|b| b.map(|b| b.to_vec().into())).map_err(|e| e.into()); let limited = LengthLimit::new(stream, max_size); let full = limited.try_concat().await.map_err(|_| anyhow::anyhow!("body too large"))?; Alternatively, manual iteration: use futures_util::StreamExt; let mut stream = response.bytes_stream(); let mut total = 0; let mut body = Vec::new(); while let Some(chunk) = stream.next().await { let chunk = chunk?; if total + chunk.len() > max_size { return Err(anyhow::anyhow!("response too large")); } total += chunk.len(); body.extend_from_slice(&chunk); } This prevents buffering the full body and enforces the limit during streaming.[3][1][4]
Citations:
- 1: https://github.com/seanmonstar/reqwest/blob/master/src/async_impl/response.rs
- 2: Add methods for making requests with response limit seanmonstar/reqwest#1234
- 3: Limit response body read size seanmonstar/reqwest#848
- 4: https://docs.rs/http-body-util/latest/http_body_util/struct.Limited.html
🏁 Script executed:
# Verify the actual file content at the specified lines
wc -l src/fetcher/nasa_apod.rsRepository: unhappychoice/splashboard
Length of output: 98
🏁 Script executed:
# Read the specific lines mentioned in the review
sed -n '253,273p' src/fetcher/nasa_apod.rsRepository: unhappychoice/splashboard
Length of output: 628
🏁 Script executed:
# Find the MAX_BYTES constant definition
rg "MAX_BYTES" src/fetcher/nasa_apod.rsRepository: unhappychoice/splashboard
Length of output: 253
🏁 Script executed:
# Check current dependencies in Cargo.toml
grep -A 5 "^\[dependencies\]" Cargo.tomlRepository: unhappychoice/splashboard
Length of output: 253
🏁 Script executed:
# Check if futures_util is already a dependency
rg "futures" Cargo.tomlRepository: unhappychoice/splashboard
Length of output: 51
🏁 Script executed:
# Get full Cargo.toml to see all dependencies
cat Cargo.tomlRepository: unhappychoice/splashboard
Length of output: 2430
🏁 Script executed:
# Check if bytes_stream() is available from reqwest without additional dependencies
rg "bytes_stream" src/Repository: unhappychoice/splashboard
Length of output: 51
🏁 Script executed:
# Look for other async stream usage patterns in the codebase
rg "StreamExt\|futures" src/ --type rsRepository: unhappychoice/splashboard
Length of output: 96
🏁 Script executed:
# Verify what HTTP methods are available from reqwest in this codebase
rg "use reqwest" src/fetcher/nasa_apod.rs -A 5Repository: unhappychoice/splashboard
Length of output: 304
🏁 Script executed:
# Check if bytes_stream() exists in reqwest without needing StreamExt
# by looking at reqwest method signatures in comments or docs
rg "bytes_stream\|from_byte_stream" src/ --type=rustRepository: unhappychoice/splashboard
Length of output: 51
🏁 Script executed:
# Check what version of reqwest is being used and if there are alternative patterns
grep -n "reqwest" Cargo.tomlRepository: unhappychoice/splashboard
Length of output: 172
🏁 Script executed:
# Look for the complete fetch_bytes function and surrounding context
sed -n '245,280p' src/fetcher/nasa_apod.rsRepository: unhappychoice/splashboard
Length of output: 1230
🏁 Script executed:
# Check if there's any streaming pattern used elsewhere in the codebase
rg "\.stream\(\)|\.chunk\(\)" src/ --type=rustRepository: unhappychoice/splashboard
Length of output: 51
🏁 Script executed:
# Verify what methods are available on reqwest::Response in version 0.12
grep -n "bytes_stream" Cargo.toml || echo "bytes_stream not in Cargo.toml"Repository: unhappychoice/splashboard
Length of output: 100
🏁 Script executed:
# Check if there's an existing streaming pattern used anywhere for size limiting
rg "take\|limit" src/fetcher/ --type=rust -B2 -A2Repository: unhappychoice/splashboard
Length of output: 51
🏁 Script executed:
# Verify the test section referenced in the review scratchpad
sed -n '642,652p' src/fetcher/nasa_apod.rsRepository: unhappychoice/splashboard
Length of output: 452
🏁 Script executed:
# Check if futures_util is used anywhere in the codebase
rg "futures_util\|futures::" src/ --type=rustRepository: unhappychoice/splashboard
Length of output: 51
🏁 Script executed:
# Verify if reqwest 0.12 Response has bytes_stream method available
# by checking what's imported from reqwest in the current file
sed -n '1,50p' src/fetcher/nasa_apod.rs | grep -E "use|import"Repository: unhappychoice/splashboard
Length of output: 493
🏁 Script executed:
# Look at the full context of how http() client is created
rg "fn http\(\)" src/fetcher/nasa_apod.rs -A 3Repository: unhappychoice/splashboard
Length of output: 209
🏁 Script executed:
# Check the file size to understand full scope
wc -l src/fetcher/nasa_apod.rsRepository: unhappychoice/splashboard
Length of output: 98
🏁 Script executed:
# Look for the rest of the fetch_bytes function to ensure we have complete picture
sed -n '253,290p' src/fetcher/nasa_apod.rsRepository: unhappychoice/splashboard
Length of output: 1137
🏁 Script executed:
# Final verification: check if bytes_stream exists on reqwest Response
rg "impl Response" --type=rust | head -5Repository: unhappychoice/splashboard
Length of output: 51
🏁 Script executed:
# Check what StreamExt provides and if there's any other way to iterate
grep -n "StreamExt\|stream" Cargo.tomlRepository: unhappychoice/splashboard
Length of output: 51
Enforce MAX_BYTES during streaming, not after full buffering.
On line 264, Response::bytes() buffers the full response body before returning, so the size check on line 267 cannot prevent memory exhaustion on oversized responses. Use bytes_stream() with manual size tracking during download to enforce the limit before buffering completes.
Suggested fix
async fn fetch_bytes(url: &str) -> Result<Vec<u8>, FetchError> {
+ use futures_util::StreamExt;
+
let res = http()
.get(url)
.send()
.await
.map_err(|e| FetchError::Failed(format!("apod image request failed: {e}")))?;
let status = res.status();
if !status.is_success() {
return Err(FetchError::Failed(format!("apod image {status}")));
}
- let bytes = res
- .bytes()
- .await
- .map_err(|e| FetchError::Failed(format!("apod image body: {e}")))?;
- if bytes.len() > MAX_BYTES {
- return Err(FetchError::Failed(format!(
- "apod image too large: {} bytes",
- bytes.len()
- )));
- }
- Ok(bytes.to_vec())
+ let mut out = Vec::new();
+ let mut total = 0usize;
+ let mut stream = res.bytes_stream();
+ while let Some(chunk) = stream.next().await {
+ let chunk = chunk.map_err(|e| FetchError::Failed(format!("apod image body: {e}")))?;
+ total = total.saturating_add(chunk.len());
+ if total > MAX_BYTES {
+ return Err(FetchError::Failed(format!(
+ "apod image too large: {} bytes",
+ total
+ )));
+ }
+ out.extend_from_slice(&chunk);
+ }
+ Ok(out)
}(Requires adding futures-util to dependencies; alternatively, iterate without StreamExt using raw .next() calls if preferred.)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/fetcher/nasa_apod.rs` around lines 253 - 273, The fetch_bytes function
currently calls Response::bytes() which buffers the entire body before checking
MAX_BYTES; change fetch_bytes to consume response.bytes_stream() and
stream-chunk-by-chunk while tracking a running total, returning
Err(FetchError::Failed(...)) immediately if total > MAX_BYTES, and otherwise
append chunks into a buffer (e.g., BytesMut or Vec<u8>) and return the collected
bytes; update the code paths that map transport errors to the same FetchError
variants and add the needed StreamExt import (or iterate with .next()) so the
size enforcement happens during download rather than after buffering.
Summary
Adds
nasa_apod, a multi-shape cached fetcher for NASA's Astronomy Picture of the Day. It feeds the shippedmedia_imagerenderer (the killer use case — a fresh curated space photo on every shell startup) plus text shapes that reshape the same single API read into the title / explanation / date metadata.nasa_apodunder meta: fetcher roadmap - Social & Media #67 "Novelty image feeds"api.nasa.govis hardcoded and the optionalapi_keyonly leaves to that known host (thegithub_*"fixed-host authenticated fetcher stays Safe" rule). The JSON response carries an arbitrary image URL string, so its host is re-validated against an allowlist before download (mirrorsrandom_dog's defense-in-depth).Imageshape errors out on those days; the text shapes still render fromtitle/explanation.api_keyis optional, falling back to theNASA_API_KEYenv var, then the sharedDEMO_KEY(rate-limited but plenty for a once-daily splash).Reference
NASA's Astronomy Picture of the Day — a fresh curated space photograph each day. The default
Imageshape renders the picture; text shapes surface the title, explanation, and date. On the occasional video day the image shape errors while text shapes still render.image,text,text_block,markdown_text_block,linked_text_block,entriesOptions
api_keyNASA_API_KEYenv var, then to the sharedDEMO_KEY(rate-limited but fine for a once-daily splash). Get a free key at api.nasa.gov.Compatible renderers
imagemedia_image,animated_boot,animated_postfx,animated_scanlines,animated_splitflap,animated_wavetexttext_plain,text_ascii,animated_typewriter,animated_figlet_morph, …text_blocklist_plain, …markdown_text_blocktext_markdownlinked_text_blocklist_linksentriesgrid_table, …Test plan
cargo fmt --all -- --checkcargo clippy --all-targets -- -D warningscargo test— 2214 pass, nasa_apod unit suite 24 tests covering all 6 shape branches, option parsing, host allowlist, video-day rejection, malformed-date handling, byte cap--ignored) downloaded today's APOD and verified magic-byte-valid image bytes.splashboard/dashboard.tomlexercising Image / Text / TextBlock / Entries shapes side by side🤖 Generated with Claude Code
Summary by CodeRabbit