Skip to content

feat(fetcher): add nasa_apod — NASA Astronomy Picture of the Day - #230

Merged
unhappychoice merged 2 commits into
mainfrom
feat/nasa-apod-fetcher
May 14, 2026
Merged

unhappychoice merged 2 commits into
mainfrom
feat/nasa-apod-fetcher

Conversation

@unhappychoice

@unhappychoice unhappychoice commented May 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds nasa_apod, a multi-shape cached fetcher for NASA's Astronomy Picture of the Day. It feeds the shipped media_image renderer (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.

  • Catalog: ticks nasa_apod under meta: fetcher roadmap - Social & Media #67 "Novelty image feeds"
  • Safety::Safe — api.nasa.gov is hardcoded and the optional api_key only leaves to that known host (the github_* "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 (mirrors random_dog's defense-in-depth).
  • Video days: APOD posts a video roughly weekly. The Image shape errors out on those days; the text shapes still render from title / explanation.
  • Config: zero-config — api_key is optional, falling back to the NASA_API_KEY env var, then the shared DEMO_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 Image shape 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.

Kind Safety Shapes
cached Safe image, text, text_block, markdown_text_block, linked_text_block, entries

Options

Option Type Required Default Description
api_key string no "DEMO_KEY" NASA API key. Falls back to the NASA_API_KEY env var, then to the shared DEMO_KEY (rate-limited but fine for a once-daily splash). Get a free key at api.nasa.gov.

Compatible renderers

Shape Renderers
image media_image, animated_boot, animated_postfx, animated_scanlines, animated_splitflap, animated_wave
text text_plain, text_ascii, animated_typewriter, animated_figlet_morph, …
text_block list_plain, …
markdown_text_block text_markdown
linked_text_block list_links
entries grid_table, …

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --all-targets -- -D warnings
  • cargo 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
  • Live test (--ignored) downloaded today's APOD and verified magic-byte-valid image bytes
  • Manual smoke test via temporary .splashboard/dashboard.toml exercising Image / Text / TextBlock / Entries shapes side by side

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added NASA Astronomy Picture of the Day (APOD) fetcher with support for multiple output formats: image, text, markdown, linked text, and entries.
    • APOD fetcher supports flexible API key configuration via options, environment variables, or demo key fallback.
    • Image downloads include host validation and automatic cache management.

Review Change Stack

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

coderabbitai Bot commented May 14, 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 52 minutes and 42 seconds before requesting another review.

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 @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: e81d252e-8592-4b2c-8295-63171db28765

📥 Commits

Reviewing files that changed from the base of the PR and between 4e98f71 and 7391d4d.

📒 Files selected for processing (1)
  • src/fetcher/nasa_apod.rs
📝 Walkthrough

Walkthrough

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

Changes

NASA APOD Fetcher

Layer / File(s) Summary
Module declaration and schema
src/fetcher/mod.rs, src/fetcher/nasa_apod.rs
Publicly exposes the nasa_apod module and defines Options schema with optional api_key, supported output Shapes (Image, Text, Markdown, LinkedText, Entries), and constants for API endpoints, allowed image hosts, timeouts, and size limits.
Fetcher trait implementation
src/fetcher/nasa_apod.rs
Implements the Fetcher trait for NasaApodFetcher, wiring catalog metadata (name, safety level, description, shapes, option schemas), cache key computation, and the main fetch orchestration logic that resolves the API key, fetches APOD JSON, and dispatches to shape-specific body builders.
API integration and key resolution
src/fetcher/nasa_apod.rs
Defines ApiResponse model for typed APOD JSON deserialization, implements API key resolution (explicit option → NASA_API_KEY env → DEMO_KEY fallback), constructs and encodes the APOD API request URL, and handles HTTP and JSON parsing errors.
Image downloading and host validation
src/fetcher/nasa_apod.rs
Implements image body rendering: validates media_type (rejects video), enforces an allowlist on the image URL host to prevent off-host downloads, downloads image bytes with maximum size enforcement, and returns raw bytes for downstream format detection and caching.
Cache management and helper functions
src/fetcher/nasa_apod.rs
Provides shared reqwest::Client singleton with user-agent and timeout configuration, detects image format via byte signature matching (PNG, JPEG, GIF, WebP), computes APOD cache directory paths, removes stale cached files for the active cache key across all known extensions, formats entries with conditional cleaned copyright text (collapsing whitespace), and constructs archive page URLs for well-formed YYYY-MM-DD dates.
Comprehensive test suite
src/fetcher/nasa_apod.rs
Unit tests for options parsing/validation, API key resolution, URL parameter encoding, host allowlist enforcement, date URL formatting, whitespace cleanup, entries inclusion/omission, image signature detection, video media rejection for image body, cache key variance, stale file removal, cache directory env override, HTTP error handling, and oversized body rejection. Includes an ignored live integration test that downloads today's APOD and validates the file format.
Registry wiring
src/fetcher/mod.rs
Registers nasa_apod::NasaApodFetcher in Registry::with_builtins(), making it available as a built-in fetcher alongside existing cached and realtime fetchers.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🌌 A rabbit hops through NASA's cosmic store,
Fetching pictures of stars and more,
With host checks tight and cache so clean,
The APOD pipeline now convenes—
Each image caught, each title bright,
Astronomy served up pixel-light! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 70.91% 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 clearly summarizes the main change: adding a new nasa_apod fetcher for NASA's Astronomy Picture of the Day, which aligns with the file additions and objectives.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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/nasa-apod-fetcher

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 May 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.13894% with 40 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.57%. Comparing base (bb1e856) to head (7391d4d).

Files with missing lines Patch % Lines
src/fetcher/nasa_apod.rs 93.12% 40 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Files with missing lines Coverage Δ
src/fetcher/mod.rs 99.14% <100.00%> (+<0.01%) ⬆️
src/fetcher/nasa_apod.rs 93.12% <93.12%> (ø)

... and 1 file 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.

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between bb1e856 and 4e98f71.

📒 Files selected for processing (2)
  • src/fetcher/mod.rs
  • src/fetcher/nasa_apod.rs

Comment thread src/fetcher/nasa_apod.rs
Comment on lines +253 to +273
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())

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 | ⚡ Quick win

🧩 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:


🏁 Script executed:

# Verify the actual file content at the specified lines
wc -l src/fetcher/nasa_apod.rs

Repository: unhappychoice/splashboard

Length of output: 98


🏁 Script executed:

# Read the specific lines mentioned in the review
sed -n '253,273p' src/fetcher/nasa_apod.rs

Repository: unhappychoice/splashboard

Length of output: 628


🏁 Script executed:

# Find the MAX_BYTES constant definition
rg "MAX_BYTES" src/fetcher/nasa_apod.rs

Repository: unhappychoice/splashboard

Length of output: 253


🏁 Script executed:

# Check current dependencies in Cargo.toml
grep -A 5 "^\[dependencies\]" Cargo.toml

Repository: unhappychoice/splashboard

Length of output: 253


🏁 Script executed:

# Check if futures_util is already a dependency
rg "futures" Cargo.toml

Repository: unhappychoice/splashboard

Length of output: 51


🏁 Script executed:

# Get full Cargo.toml to see all dependencies
cat Cargo.toml

Repository: 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 rs

Repository: 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 5

Repository: 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=rust

Repository: 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.toml

Repository: 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.rs

Repository: 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=rust

Repository: 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 -A2

Repository: 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.rs

Repository: unhappychoice/splashboard

Length of output: 452


🏁 Script executed:

# Check if futures_util is used anywhere in the codebase
rg "futures_util\|futures::" src/ --type=rust

Repository: 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 3

Repository: unhappychoice/splashboard

Length of output: 209


🏁 Script executed:

# Check the file size to understand full scope
wc -l src/fetcher/nasa_apod.rs

Repository: 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.rs

Repository: unhappychoice/splashboard

Length of output: 1137


🏁 Script executed:

# Final verification: check if bytes_stream exists on reqwest Response
rg "impl Response" --type=rust | head -5

Repository: 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.toml

Repository: 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.

Comment thread src/fetcher/nasa_apod.rs Resolved
@unhappychoice
unhappychoice merged commit 1b62650 into main May 14, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the feat/nasa-apod-fetcher branch May 14, 2026 07:51
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.

1 participant