Skip to content

feat(fetcher): add calendar_holidays — Nager.Date-backed public holidays - #155

Merged
unhappychoice merged 1 commit into
mainfrom
feat/calendar-holidays
Apr 26, 2026
Merged

unhappychoice merged 1 commit into
mainfrom
feat/calendar-holidays

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds calendar_holidays, a single fetcher under the new calendar_* family that emits Calendar / Text / TextBlock from one Nager.Date API call. Collapses the planned holiday_today + holiday_upcoming checkboxes (#68) into one widget — same underlying read, three shapes:

  • Calendar (default) — current month, today highlighted, holiday days populated as events
  • Text — today's holiday name (🎌 Showa Day), or empty (renders as the shared "nothing here yet" placeholder)
  • TextBlock — next N upcoming holidays (04/29 — Showa Day)

Targets the home_feed morning-briefing preset (#150) ambient slot. Updates #68 post-merge: drop the holiday_* section, add calendar_holidays to calendar_*.

Reference

  • Kind: cached
  • Safety: Safe — host date.nager.at hardcoded; only ISO 3166-1 alpha-2 country code is config-driven and validated locally (filter to letters → uppercase → require length 2)
  • Shapes: calendar, text, text_block

Options

Option Type Required Default Description
country string (ISO 3166-1 alpha-2, e.g. \"JP\" / \"US\") yes — Country whose public holidays to fetch.
language \"local\" | \"english\" no \"local\" Display-name source. local uses the country's localized name; english uses the English label.
limit integer (1..=30) no 5 Maximum number of upcoming holidays to list (TextBlock shape only).

Compatible renderers

Shape Renderers
calendar grid_calendar + animated families
text text_plain, text_ascii + animated families
text_block list_plain, text_plain + animated families

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --all-targets -- -D warnings
  • cargo test — 765 tests green (21 new in fetcher::calendar::holidays::tests)
  • Live API smoke (#[ignore] test against date.nager.at) returns 16 JP holidays for 2026
  • Local smoke-test dashboard with 4 widgets exercising all 3 shapes + language toggle — renders correctly (today empty → placeholder, upcoming sorted, calendar marks 04/29 as event day)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added a holidays calendar fetcher that retrieves and displays public holidays by country, with options to customize the display format and language.

…Date

Single fetcher under the new `calendar_*` family that emits Calendar / Text /
TextBlock from one underlying API read. Replaces the planned `holiday_today` +
`holiday_upcoming` checkboxes (#68) with one widget covering today's holiday,
upcoming list, and a month grid with holiday days flagged as event_days.

Safety::Safe — host `date.nager.at` is hardcoded; only the ISO 3166-1 alpha-2
country code is config-driven and is sanitised locally.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

A new CalendarHolidaysFetcher module is introduced that retrieves public holiday data from an external API. The fetcher supports multiple output shapes and configurable options, with integration into the existing fetcher registry system.

Changes

Cohort / File(s) Summary
Calendar Fetcher Implementation
src/fetcher/calendar/holidays.rs
Implements CalendarHolidaysFetcher struct with public holiday fetching from date.nager.at, supporting Calendar/Text/TextBlock shapes, configurable country/language/limit options, HTTP client with timeout/user-agent, and comprehensive unit tests.
Module Setup & Registration
src/fetcher/calendar/mod.rs, src/fetcher/mod.rs
Defines new calendar module with public holidays submodule and fetchers() factory function; registers calendar fetchers in main fetcher registry.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • PR #88: Also adds new fetcher modules and registers them in src/fetcher/mod.rs, extending the fetcher registry with similar structural patterns.

Poem

🐰✨ A calendar now hops with holiday cheer,
With countries and dates throughout the year!
From API to text, in shapes so fine,
Our fetcher now marks each celebration divine! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.14% 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 and specifically describes the main change: adding a calendar_holidays fetcher backed by Nager.Date API, covering the primary addition in the changeset.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/calendar-holidays

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 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.65385% with 51 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.25%. Comparing base (c4e8ee2) to head (43aafe6).
⚠️ Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
src/fetcher/calendar/holidays.rs 83.66% 50 Missing ⚠️
src/fetcher/mod.rs 66.66% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #155      +/-   ##
==========================================
+ Coverage   78.08%   78.25%   +0.16%     
==========================================
  Files         112      115       +3     
  Lines       21018    21690     +672     
==========================================
+ Hits        16412    16973     +561     
- Misses       4606     4717     +111     
Files with missing lines Coverage Δ
src/fetcher/calendar/mod.rs 100.00% <100.00%> (ø)
src/fetcher/mod.rs 84.10% <66.66%> (+0.61%) ⬆️
src/fetcher/calendar/holidays.rs 83.66% <83.66%> (ø)

... and 5 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.

@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

🧹 Nitpick comments (2)
src/fetcher/calendar/holidays.rs (2)

477-487: Nit: live test runs deserialization but not formatting end-to-end.

The ignored live test only prints the raw rows. Since the whole point of the smoke test is "does my pipeline still work against real Nager.Date data," consider also running render_body(&holidays, Shape::TextBlock, today, Language::Local, 5) and asserting non-empty lines. Optional.

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

In `@src/fetcher/calendar/holidays.rs` around lines 477 - 487, Update the live
smoke test live_jp_returns_holidays_for_current_year to exercise end-to-end
formatting: after calling fetch_year(today.year(), "JP") and asserting non-empty
holidays, call render_body(&holidays, Shape::TextBlock, today, Language::Local,
5) and assert that the returned lines (or rendered string) are non-empty; this
ensures the pipeline covers deserialization and formatting (referenced symbols:
fetch_year, render_body, Shape::TextBlock, Language::Local).

56-72: Minor: language field is Option<Language> but the enum derives Default.

Since Language already implements Default (= Local), language: Language with #[serde(default)] is equivalent and removes one unwrap site at line 116. Pure ergonomics; not blocking.

♻️ Sketch
 pub struct Options {
     pub country: Option<String>,
     #[serde(default)]
-    pub language: Option<Language>,
+    pub language: Language,
     #[serde(default)]
     pub limit: Option<u32>,
 }

…and at line 116:

-        let language = opts.language.unwrap_or_default();
+        let language = opts.language;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/calendar/holidays.rs` around lines 56 - 72, Change
Options.language from Option<Language> to Language with #[serde(default)] and
remove the Option wrapper so serde supplies Language::Local when absent; update
any code that currently does .language.unwrap() (the usage site that unwraps
Options.language) to use the field directly (or adjust to .language if binding
changed), and ensure imports/derives remain the same for the Language enum which
already implements Default.
🤖 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/calendar/holidays.rs`:
- Around line 88-95: The cache key generation in fn cache_key(&self, ctx:
&FetchContext) omits the current year, allowing stale cross-year reads; modify
cache_key to incorporate the current UTC year (e.g., obtain Utc::now().year())
into the extra string used when calling cache_key(self.name(), ctx, &extra) so
the key becomes unique per year; ensure you still include the existing
toml-serialized ctx.options and fall back to the same default behavior when
options are None.
- Around line 113-127: The fetch function in holidays.rs currently only calls
fetch_year(today.year()) which causes TextBlock/upcoming_lines to run dry at
year-end; modify fetch to also retrieve the next year (fetch_year(today.year() +
1)) when the cursor is within ~limit days of year-end or unconditionally, merge
the two holiday vectors into the holidays variable before any
filtering/rendering, and ensure shape (ctx.shape / Shape::Calendar) is bound
before the fetches so you can decide conditional fetching by shape; update the
call sites using holidays (e.g., render_body) to use the merged list and keep
the existing >= today filtering logic.

---

Nitpick comments:
In `@src/fetcher/calendar/holidays.rs`:
- Around line 477-487: Update the live smoke test
live_jp_returns_holidays_for_current_year to exercise end-to-end formatting:
after calling fetch_year(today.year(), "JP") and asserting non-empty holidays,
call render_body(&holidays, Shape::TextBlock, today, Language::Local, 5) and
assert that the returned lines (or rendered string) are non-empty; this ensures
the pipeline covers deserialization and formatting (referenced symbols:
fetch_year, render_body, Shape::TextBlock, Language::Local).
- Around line 56-72: Change Options.language from Option<Language> to Language
with #[serde(default)] and remove the Option wrapper so serde supplies
Language::Local when absent; update any code that currently does
.language.unwrap() (the usage site that unwraps Options.language) to use the
field directly (or adjust to .language if binding changed), and ensure
imports/derives remain the same for the Language enum which already implements
Default.
🪄 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: 322de3ab-ee3c-4725-b176-b7b15e494210

📥 Commits

Reviewing files that changed from the base of the PR and between 0d5ebb2 and 43aafe6.

📒 Files selected for processing (3)
  • src/fetcher/calendar/holidays.rs
  • src/fetcher/calendar/mod.rs
  • src/fetcher/mod.rs

Comment on lines +88 to +95
fn cache_key(&self, ctx: &FetchContext) -> String {
let extra = ctx
.options
.as_ref()
.and_then(|v| toml::to_string(v).ok())
.unwrap_or_default();
cache_key(self.name(), ctx, &extra)
}

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

Cache key omits the year — risk of stale cross-year reads.

cache_key mixes in name + shape + format + options but not today.year(). If the cache TTL outlives Jan 1 00:00 UTC, a January read can hit the previous year's cached payload and upcoming_lines will yield nothing until the entry expires. Folding Utc::now().year() into the extra string makes the boundary deterministic.

♻️ Suggested fix
     fn cache_key(&self, ctx: &FetchContext) -> String {
-        let extra = ctx
-            .options
-            .as_ref()
-            .and_then(|v| toml::to_string(v).ok())
-            .unwrap_or_default();
-        cache_key(self.name(), ctx, &extra)
+        let opts = ctx
+            .options
+            .as_ref()
+            .and_then(|v| toml::to_string(v).ok())
+            .unwrap_or_default();
+        let year = chrono::Utc::now().date_naive().year();
+        cache_key(self.name(), ctx, &format!("{year}|{opts}"))
     }
📝 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
fn cache_key(&self, ctx: &FetchContext) -> String {
let extra = ctx
.options
.as_ref()
.and_then(|v| toml::to_string(v).ok())
.unwrap_or_default();
cache_key(self.name(), ctx, &extra)
}
fn cache_key(&self, ctx: &FetchContext) -> String {
let opts = ctx
.options
.as_ref()
.and_then(|v| toml::to_string(v).ok())
.unwrap_or_default();
let year = chrono::Utc::now().date_naive().year();
cache_key(self.name(), ctx, &format!("{year}|{opts}"))
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/calendar/holidays.rs` around lines 88 - 95, The cache key
generation in fn cache_key(&self, ctx: &FetchContext) omits the current year,
allowing stale cross-year reads; modify cache_key to incorporate the current UTC
year (e.g., obtain Utc::now().year()) into the extra string used when calling
cache_key(self.name(), ctx, &extra) so the key becomes unique per year; ensure
you still include the existing toml-serialized ctx.options and fall back to the
same default behavior when options are None.

Comment on lines +113 to +127
async fn fetch(&self, ctx: &FetchContext) -> Result<Payload, FetchError> {
let opts: Options = parse_options(ctx.options.as_ref()).map_err(FetchError::Failed)?;
let country = require_country(opts.country.as_deref())?;
let language = opts.language.unwrap_or_default();
let limit = opts
.limit
.unwrap_or(DEFAULT_LIMIT)
.clamp(MIN_LIMIT, MAX_LIMIT) as usize;
let today = Utc::now().date_naive();
let holidays = fetch_year(today.year(), &country).await?;
let shape = ctx.shape.unwrap_or(Shape::Calendar);
Ok(payload(render_body(
&holidays, shape, today, language, limit,
)))
}

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

Year-boundary blind spot: TextBlock will dry up at year-end.

fetch_year(today.year(), …) only ever asks Nager.Date for the current calendar year. In late December, upcoming_lines will return zero or one entries even though early-January holidays are publicly available from the same endpoint (/api/v3/PublicHolidays/{year+1}/{country}). This silently degrades the home-feed morning briefing for ~weeks every year-end. Today/Calendar shapes are unaffected, but the TextBlock shape is the one most likely to surface the gap.

Consider fetching the next year too whenever the cursor is within ~limit holiday-days of year-end (or unconditionally — it's one extra cached request per year), then merging before filtering by >= today.

♻️ Sketch
-        let today = Utc::now().date_naive();
-        let holidays = fetch_year(today.year(), &country).await?;
+        let today = Utc::now().date_naive();
+        let mut holidays = fetch_year(today.year(), &country).await?;
+        if matches!(shape, Shape::TextBlock) {
+            // Carry over next year's data so December → January upcoming lists keep working.
+            if let Ok(next) = fetch_year(today.year() + 1, &country).await {
+                holidays.extend(next);
+            }
+        }
         let shape = ctx.shape.unwrap_or(Shape::Calendar);

(Move the shape binding above the fetch.)

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

In `@src/fetcher/calendar/holidays.rs` around lines 113 - 127, The fetch function
in holidays.rs currently only calls fetch_year(today.year()) which causes
TextBlock/upcoming_lines to run dry at year-end; modify fetch to also retrieve
the next year (fetch_year(today.year() + 1)) when the cursor is within ~limit
days of year-end or unconditionally, merge the two holiday vectors into the
holidays variable before any filtering/rendering, and ensure shape (ctx.shape /
Shape::Calendar) is bound before the fetches so you can decide conditional
fetching by shape; update the call sites using holidays (e.g., render_body) to
use the merged list and keep the existing >= today filtering logic.

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