Skip to content

feat(fetcher): split clock into clock_* sibling fetchers - #51

Merged
unhappychoice merged 1 commit into
mainfrom
feat/clock-options
Apr 22, 2026
Merged

unhappychoice merged 1 commit into
mainfrom
feat/clock-options

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Adds generic options: Option<toml::Value> on WidgetConfig / FetchContext so each fetcher deserializes its own typed [widget.options] sub-table. Reusable by future fetchers — no per-option typed fields sprawling on WidgetConfig.
  • Splits temporal features into sibling fetchers under a clock_* prefix rather than one fat fetcher with mode dispatch. Same read primitives are shared via clock/common.rs; each fetcher has a narrow Options struct and a small shapes() list. Every options struct uses deny_unknown_fields so typos surface as placeholders instead of silent wrong renders.
fetcher shapes options
clock Lines / Entries / Calendar timezone, events
clock_timezones Lines / Entries timezones = [...]
clock_countdown Lines / Entries target or targets = [...], target_label
clock_ratio Ratio period = \"day\"|\"year\"|\"month\"|\"week\"|\"quarter\"|\"hour\"
clock_state Badge kind = \"business_hours\"|\"weekend\"|\"night\"
clock_sunrise Lines / Entries lat, lon, timezone
clock_derived Lines kind = \"moon_phase\"|\"zodiac\"|\"chinese_zodiac\"|\"season\"|\"jp_season\"|\"rokuyou\"|\"iso_week\"|\"day_of_year\"|\"julian_day\"|\"unix_epoch\"|\"time_of_day\"
  • Adds one new dep: chrono-tz (IANA DB).
  • Dogfoods 6 new widgets in .splashboard/config.toml (world clock, year progress gauge, business-hours badge, moon phase, Tokyo sunrise/sunset, New Year countdown).

Design note

An earlier iteration consolidated all of this into one clock fetcher with a Mode enum dispatching on options. The implementation revealed that mode-dispatch + broad Options + per-mode shape validation was heavier than splitting, and docs catalog (#52) will benefit from one fetcher = one coherent page. Matches the established system / cpu_load / memory split pattern.

Refs #41.

Test plan

  • cargo test — 258 passed, 0 failed (covers options parsing, deny_unknown_fields rejection, per-fetcher shape / option matrices, fraction correctness at period boundaries, sunrise plausibility for Tokyo).
  • cargo clippy --all-targets -- -D warnings clean.
  • cargo fmt --all --check clean.
  • cargo run in the repo renders the dogfood config with all new widgets.

🤖 Generated with Claude Code

@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 19 minutes and 41 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 19 minutes and 41 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: 5e8c2a3c-2ad1-4961-928e-1feceea16d6c

📥 Commits

Reviewing files that changed from the base of the PR and between b478643 and bcd5523.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (14)
  • .splashboard/config.toml
  • Cargo.toml
  • src/config.rs
  • src/fetcher/clock.rs
  • src/fetcher/clock/common.rs
  • src/fetcher/clock/countdown.rs
  • src/fetcher/clock/derived.rs
  • src/fetcher/clock/mod.rs
  • src/fetcher/clock/ratio.rs
  • src/fetcher/clock/state.rs
  • src/fetcher/clock/sunrise.rs
  • src/fetcher/clock/timezones.rs
  • src/fetcher/mod.rs
  • src/runtime.rs
📝 Walkthrough

Walkthrough

The PR restructures the clock fetcher from a monolithic module into a modular architecture supporting multiple rendering modes (countdown, timezone display, sunrise/sunset, state badges, ratio gauges, and derived calendar values). A new chrono-tz dependency enables timezone-aware computation, while a unified options parser dispatches across specialized sub-modules to generate appropriate output shapes.

Changes

Cohort / File(s) Summary
Configuration & Manifest
.splashboard/config.toml, Cargo.toml
Added chrono-tz 0.10 dependency and six new clock-based widgets (world_clock, year_progress, business_hours, moon, sun, newyear_countdown) with corresponding layout rows and render types.
Core Config & Runtime
src/config.rs, src/fetcher/mod.rs, src/runtime.rs
Added options: Option<toml::Value> field to WidgetConfig and FetchContext to carry widget-specific TOML configuration; updated runtime to populate options into fetch context.
Clock Fetcher Restructuring
src/fetcher/clock/mod.rs
Rewrote ClockFetcher implementation with mode-based dispatch logic supporting Lines, Entries, Calendar, Ratio, and Badge shapes; replaced monolithic logic with modular sub-module delegation.
Options Parsing & Mode Selection
src/fetcher/clock/options.rs
New module defining strongly-typed Options struct with selectors for timezone, timezones, target(s), ratio, state, derived, sunrise/sunset, and calendar; implements mode selection, shape validation, and timezone-aware DateTime computation via chrono-tz.
Rendering Modules
src/fetcher/clock/countdown.rs, src/fetcher/clock/derived.rs, src/fetcher/clock/format.rs, src/fetcher/clock/ratio.rs, src/fetcher/clock/state.rs, src/fetcher/clock/sunrise.rs, src/fetcher/clock/timezones.rs
Seven new specialized renderers: countdown parses RFC3339/date targets and formats remaining time; derived generates moon phase, zodiac, season, and other astronomical/calendar values; format provides strftime-style safe formatting; ratio computes day/hour/week/month/quarter/year fractions; state renders business-hours/weekend/night predicates as badges; sunrise computes solar events; timezones formats multi-timezone strips.

Sequence Diagram

sequenceDiagram
    participant Widget as Widget Config
    participant Runtime as Runtime
    participant Fetcher as ClockFetcher
    participant Options as Options Parser
    participant Renderer as Mode Renderer<br/>(countdown/derived/ratio/etc)
    participant Output as Body Output

    Widget->>Runtime: fetch with options
    Runtime->>Fetcher: compute(FetchContext{options})
    Fetcher->>Options: parse(ctx.options)
    alt Valid Options
        Options->>Fetcher: Options{mode, timezone, ...}
        Fetcher->>Fetcher: validate_shape(mode, shape)
        alt Shape Valid
            Fetcher->>Renderer: dispatch to mode-specific renderer
            Renderer->>Renderer: compute current time (timezone-aware)
            Renderer->>Output: generate Body::Lines/Entries/Ratio/Badge/Calendar
        else Shape Invalid
            Fetcher->>Output: fallback placeholder body
        end
    else Parse Error
        Fetcher->>Output: fallback placeholder body with error hint
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 Hop through timezones with glee,
Modular clocks now run free!
Countdowns tick and moon phases gleam,
Sunrise dawns across each stream 🌍✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 49.58% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ⚠️ Warning The PR title claims to 'split clock into clock_* sibling fetchers', but the actual change refactors clock into a single multi-mode fetcher with options, not separate sibling fetchers. Update the title to accurately reflect the change: 'refactor(fetcher): add multi-mode clock fetcher with options' or similar.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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/clock-options

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/fetcher/mod.rs (1)

122-128: ⚠️ Potential issue | 🟡 Minor

default_cache_key ignores ctx.options — latent cache-coherency hazard once a cached fetcher starts using options.

Clock is a RealtimeFetcher so it's safe today, but FetchContext.options is exposed to all fetchers including Cached(_). The moment a cached fetcher keys its output off options (e.g. a future read_store filter, or a network fetcher with URL-via-options), two widgets differing only in [widget.options] will share a cache file and stomp each other's payloads.

Either mix a stable serialization of options into the default key now, or leave a guard so cached fetchers that use options must override cache_key. Worth a short note either way.

🔧 Possible fix
 pub fn default_cache_key(name: &str, ctx: &FetchContext) -> String {
     use sha2::{Digest, Sha256};
-    let raw = format!("{}|{}", name, ctx.format.as_deref().unwrap_or(""));
+    let opts = ctx
+        .options
+        .as_ref()
+        .map(|v| v.to_string())
+        .unwrap_or_default();
+    let raw = format!("{}|{}|{}", name, ctx.format.as_deref().unwrap_or(""), opts);
     let digest = Sha256::digest(raw.as_bytes());
     let hex: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect();
     format!("{name}-{hex}")
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/mod.rs` around lines 122 - 128, The default_cache_key
implementation for default_cache_key(name: &str, ctx: &FetchContext) currently
ignores ctx.options; update it to incorporate a stable serialization of
ctx.options into the cache key (or reject use of the default when options is
non-empty). Specifically, when building the raw string, include a deterministic
representation of ctx.options (e.g., canonical JSON with sorted keys or a sorted
key-value join) so that two FetchContext instances that differ only by options
produce different keys; alternatively, add a guard in default_cache_key to panic
or return a distinct marker when ctx.options is non-empty and document that
fetchers using options must implement their own cache_key. Ensure you modify
only default_cache_key and reference ctx.options and ctx.format in the new key
composition.
♻️ Duplicate comments (1)
src/config.rs (1)

48-52: ⚠️ Potential issue | 🟡 Minor

Same doc/behavior mismatch as FetchContext.options.

"Unknown keys are ignored so upgrading the fetcher never invalidates old configs" overstates the guarantee — clock's options use deny_unknown_fields, so typos there fail parsing. Align with whatever wording you land on for src/fetcher/mod.rs Lines 56–58.

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

In `@src/config.rs` around lines 48 - 52, Update the doc comment for the options
field to remove the absolute guarantee that "unknown keys are ignored so
upgrading the fetcher never invalidates old configs" and instead mirror the
wording used for FetchContext.options in fetcher/mod.rs (lines ~56–58);
specifically, explain that options are provided as a TOML sub-table
(`[widget.options]`) and while the top-level behavior treats unknown keys as
ignored for toml::Value, specific fetcher option structs may use
deny_unknown_fields and thus can still reject unknown keys—adjust the comment on
the `options` field (pub options: Option<toml::Value>) to reflect this nuance.
🧹 Nitpick comments (1)
src/fetcher/clock/ratio.rs (1)

48-57: Dead fallback in month_fraction: from_ymd_opt(year, month, 1) can't fail for a month from now.month().

chrono::Datelike::month() is always in 1..=12, and day 1 is always valid for every month, so the unwrap_or_else(|| from_ymd_opt(year, 1, 1)…) branch is unreachable. Same idea could simplify next_month_start's trailing unwrap_or_else (Lines 88). A plain .expect("month 1..=12 with day 1 is always valid") (or .unwrap(), consistent with quarter_fraction/year_fraction) documents the invariant without the phantom recovery path.

♻️ Suggested simplification
-    let month_start = NaiveDate::from_ymd_opt(now.year(), now.month(), 1).unwrap_or_else(|| {
-        NaiveDate::from_ymd_opt(now.year(), 1, 1).expect("year start always valid")
-    });
+    let month_start = NaiveDate::from_ymd_opt(now.year(), now.month(), 1)
+        .expect("month 1..=12 with day 1 is always valid");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/clock/ratio.rs` around lines 48 - 57, The fallback in
month_fraction is unreachable because DateTime::month() returns 1..=12 and day 1
is always valid; replace the unwrap_or_else(...) used on
NaiveDate::from_ymd_opt(now.year(), now.month(), 1) with a direct expect (or
unwrap) documenting the invariant (e.g., expect("month 1..=12 with day 1 is
always valid")), and apply the same simplification to the similar unwrap_or_else
in next_month_start so code matches the style used in
quarter_fraction/year_fraction.
🤖 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/clock/derived.rs`:
- Around line 139-146: The code initializes current to the hardcoded "小寒",
causing Jan 1–5 to incorrectly show 小寒; change the logic in the jp_season (or
the function containing let (m, d) = (now.month(), now.day())) so that instead
of defaulting to "小寒" you set current to the last entry in TERMS (the previous
year's final term) or explicitly check if (m,d) is before the first TERMS
boundary and then assign current = TERMS.last().name; then proceed with the
existing loop over TERMS to overwrite when appropriate. Ensure you reference
TERMS and the local current variable when making the change.

In `@src/fetcher/clock/options.rs`:
- Around line 56-60: Add the serde attribute to reject unknown fields for the
nested struct: annotate the TargetEntry struct (the one with #[derive(Debug,
Clone, Deserialize)]) with #[serde(deny_unknown_fields)] so that deserialization
of TargetEntry rejects any unexpected keys (e.g., extra "typo" fields) instead
of silently ignoring them.

In `@src/fetcher/clock/sunrise.rs`:
- Around line 35-43: The compute function incorrectly applies a single
FixedOffset from opts.timezone_now() to both solar events, which breaks DST
transitions; update compute to convert each UTC event (the up and down values
from solar_events) using the configured timezone (e.g., parse or use the
chrono_tz::Tz from Options) to get zone-aware local DateTimes per event, and
only fall back to using the FixedOffset via to_local when no Tz is available;
adjust calls around solar_events, to_local, and timezone_now/Options so each
event is converted through the timezone-aware path independently.

In `@src/fetcher/clock/timezones.rs`:
- Around line 36-48: The zoned_times() function should capture Utc::now() once
and reuse that instant for every timezone instead of calling Utc::now() inside
resolve() per-iteration; change resolve(name: &str) ->
Option<DateTime<FixedOffset>> to accept the instant (e.g., resolve(name: &str,
instant: DateTime<Utc>)) and have zoned_times() call let now = Utc::now(); then
map each timezone to (name.clone(), resolve(name, now)); ensure resolve projects
the provided instant into the zone with with_timezone(&tz).fixed_offset(), and
update any tests to pass the captured instant accordingly to keep the realtime
path infallible and fast.

In `@src/fetcher/mod.rs`:
- Around line 56-58: The field `pub options: Option<toml::Value>` in
src/fetcher/mod.rs currently has a doc comment claiming "unknown keys are
ignored", but concrete consumers like the clock `Options` in
src/fetcher/clock/options.rs use `#[serde(deny_unknown_fields)]` so unknown keys
are rejected; update the doc for `options` to remove the incorrect "ignored"
claim and instead state that each fetcher decides strict vs lenient
deserialization (or explicitly note that some fetchers may deny unknown fields),
and make the same corresponding wording change in the similar note in
src/config.rs so docs match actual behavior and callers like the clock `Options`
using `deny_unknown_fields` are accurately described.

---

Outside diff comments:
In `@src/fetcher/mod.rs`:
- Around line 122-128: The default_cache_key implementation for
default_cache_key(name: &str, ctx: &FetchContext) currently ignores ctx.options;
update it to incorporate a stable serialization of ctx.options into the cache
key (or reject use of the default when options is non-empty). Specifically, when
building the raw string, include a deterministic representation of ctx.options
(e.g., canonical JSON with sorted keys or a sorted key-value join) so that two
FetchContext instances that differ only by options produce different keys;
alternatively, add a guard in default_cache_key to panic or return a distinct
marker when ctx.options is non-empty and document that fetchers using options
must implement their own cache_key. Ensure you modify only default_cache_key and
reference ctx.options and ctx.format in the new key composition.

---

Duplicate comments:
In `@src/config.rs`:
- Around line 48-52: Update the doc comment for the options field to remove the
absolute guarantee that "unknown keys are ignored so upgrading the fetcher never
invalidates old configs" and instead mirror the wording used for
FetchContext.options in fetcher/mod.rs (lines ~56–58); specifically, explain
that options are provided as a TOML sub-table (`[widget.options]`) and while the
top-level behavior treats unknown keys as ignored for toml::Value, specific
fetcher option structs may use deny_unknown_fields and thus can still reject
unknown keys—adjust the comment on the `options` field (pub options:
Option<toml::Value>) to reflect this nuance.

---

Nitpick comments:
In `@src/fetcher/clock/ratio.rs`:
- Around line 48-57: The fallback in month_fraction is unreachable because
DateTime::month() returns 1..=12 and day 1 is always valid; replace the
unwrap_or_else(...) used on NaiveDate::from_ymd_opt(now.year(), now.month(), 1)
with a direct expect (or unwrap) documenting the invariant (e.g., expect("month
1..=12 with day 1 is always valid")), and apply the same simplification to the
similar unwrap_or_else in next_month_start so code matches the style used in
quarter_fraction/year_fraction.
🪄 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: c7ac2c49-f58f-4c58-a6d6-78ab57a5e280

📥 Commits

Reviewing files that changed from the base of the PR and between 6ada113 and b478643.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (15)
  • .splashboard/config.toml
  • Cargo.toml
  • src/config.rs
  • src/fetcher/clock.rs
  • src/fetcher/clock/countdown.rs
  • src/fetcher/clock/derived.rs
  • src/fetcher/clock/format.rs
  • src/fetcher/clock/mod.rs
  • src/fetcher/clock/options.rs
  • src/fetcher/clock/ratio.rs
  • src/fetcher/clock/state.rs
  • src/fetcher/clock/sunrise.rs
  • src/fetcher/clock/timezones.rs
  • src/fetcher/mod.rs
  • src/runtime.rs
💤 Files with no reviewable changes (1)
  • src/fetcher/clock.rs

Comment on lines +139 to +146
let (m, d) = (now.month(), now.day());
let mut current = "小寒";
for &(tm, td, name) in TERMS {
if (m, d) >= (tm, td) {
current = name;
}
}
current.into()

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

jp_season returns 小寒 for Jan 1–5, but those dates belong to the previous year's 冬至.

The current = "小寒" default only applies when no term boundary has been crossed yet this year, which for early January means the widget shows 小寒 a few days before its actual start (Jan 6). The correct seed for Jan 1–5 is 冬至 (carried over from the previous year's Dec 22 boundary).

The module comment already acknowledges ±1-day drift, so this is minor — flagging because it's a multi-day deviation at a predictable window, not the ±1-day drift advertised.

🔧 Suggested fix
-    let (m, d) = (now.month(), now.day());
-    let mut current = "小寒";
-    for &(tm, td, name) in TERMS {
-        if (m, d) >= (tm, td) {
-            current = name;
-        }
-    }
-    current.into()
+    let (m, d) = (now.month(), now.day());
+    // Seed with 冬至 so Jan 1–5 (before 小寒 on Jan 6) reports the previous year's last term.
+    let mut current = "冬至";
+    for &(tm, td, name) in TERMS {
+        if (m, d) >= (tm, td) {
+            current = name;
+        }
+    }
+    current.into()
📝 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
let (m, d) = (now.month(), now.day());
let mut current = "小寒";
for &(tm, td, name) in TERMS {
if (m, d) >= (tm, td) {
current = name;
}
}
current.into()
let (m, d) = (now.month(), now.day());
// Seed with 冬至 so Jan 1–5 (before 小寒 on Jan 6) reports the previous year's last term.
let mut current = "冬至";
for &(tm, td, name) in TERMS {
if (m, d) >= (tm, td) {
current = name;
}
}
current.into()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/clock/derived.rs` around lines 139 - 146, The code initializes
current to the hardcoded "小寒", causing Jan 1–5 to incorrectly show 小寒; change
the logic in the jp_season (or the function containing let (m, d) =
(now.month(), now.day())) so that instead of defaulting to "小寒" you set current
to the last entry in TERMS (the previous year's final term) or explicitly check
if (m,d) is before the first TERMS boundary and then assign current =
TERMS.last().name; then proceed with the existing loop over TERMS to overwrite
when appropriate. Ensure you reference TERMS and the local current variable when
making the change.

Comment thread src/fetcher/clock/options.rs Outdated
Comment on lines +56 to +60
#[derive(Debug, Clone, Deserialize)]
pub struct TargetEntry {
pub label: String,
pub target: String,
}

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
# Verify nested target-entry validation is declared.
# Expected after the fix: TargetEntry has #[serde(deny_unknown_fields)] immediately above it.
rg -n -C3 'deny_unknown_fields|struct TargetEntry' --type=rust

Repository: unhappychoice/splashboard

Length of output: 1412


Add #[serde(deny_unknown_fields)] to TargetEntry.

Options rejects unknown top-level keys, but nested TargetEntry accepts extra fields. This inconsistency allows silent config errors like targets = [{ label = "x", target = "2099-01-01", typo = true }] where typo is silently ignored instead of rejected.

Proposed fix
 #[derive(Debug, Clone, Deserialize)]
+#[serde(deny_unknown_fields)]
 pub struct TargetEntry {
     pub label: String,
     pub target: String,
 }
📝 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
#[derive(Debug, Clone, Deserialize)]
pub struct TargetEntry {
pub label: String,
pub target: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TargetEntry {
pub label: String,
pub target: String,
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/clock/options.rs` around lines 56 - 60, Add the serde attribute
to reject unknown fields for the nested struct: annotate the TargetEntry struct
(the one with #[derive(Debug, Clone, Deserialize)]) with
#[serde(deny_unknown_fields)] so that deserialization of TargetEntry rejects any
unexpected keys (e.g., extra "typo" fields) instead of silently ignoring them.

Comment thread src/fetcher/clock/sunrise.rs Outdated
Comment on lines +35 to +43
fn compute(opts: &Options) -> Result<(DateTime<FixedOffset>, DateTime<FixedOffset>), String> {
let lat = opts.lat.ok_or("lat required")?;
let lon = opts.lon.ok_or("lon required")?;
let now = opts.timezone_now();
let date = now.date_naive();
let offset = *now.offset();
let (up, down) =
solar_events(date, lat, lon).ok_or("no sunrise/sunset at this latitude today")?;
Ok((to_local(date, up, offset), to_local(date, down, offset)))

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
# Verify the fixed-offset path used by sunrise/sunset conversion.
# Expected: sunrise.rs calls Options::timezone_now() and passes a FixedOffset into to_local().
rg -n -C3 'timezone_now|to_local|FixedOffset' --type=rust

Repository: unhappychoice/splashboard

Length of output: 24396


Use timezone-aware conversion per event to handle DST transitions correctly.

The code extracts a single FixedOffset from opts.timezone_now() and applies it to both sunrise and sunset UTC times. On DST transition days, sunrise and sunset can correspond to different local offsets, producing one-hour errors. Instead, when a timezone is configured, convert each UTC event directly through chrono_tz::Tz to preserve DST rules. Fall back to FixedOffset only when no valid zone is available.

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

In `@src/fetcher/clock/sunrise.rs` around lines 35 - 43, The compute function
incorrectly applies a single FixedOffset from opts.timezone_now() to both solar
events, which breaks DST transitions; update compute to convert each UTC event
(the up and down values from solar_events) using the configured timezone (e.g.,
parse or use the chrono_tz::Tz from Options) to get zone-aware local DateTimes
per event, and only fall back to using the FixedOffset via to_local when no Tz
is available; adjust calls around solar_events, to_local, and
timezone_now/Options so each event is converted through the timezone-aware path
independently.

Comment thread src/fetcher/clock/timezones.rs Outdated
Comment on lines +36 to +48
fn zoned_times(opts: &Options) -> Vec<(String, Option<DateTime<FixedOffset>>)> {
opts.timezones
.as_deref()
.unwrap_or(&[])
.iter()
.map(|name| (name.clone(), resolve(name)))
.collect()
}

fn resolve(name: &str) -> Option<DateTime<FixedOffset>> {
let tz: chrono_tz::Tz = name.parse().ok()?;
Some(Utc::now().with_timezone(&tz).fixed_offset())
}

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

Capture Utc::now() once for the whole world-clock strip.

Calling Utc::now() once per timezone can render rows from different instants when a tick crosses a second/minute boundary, and it adds avoidable work on the realtime path. Capture one timestamp in zoned_times() and project that same instant into every zone. Based on learnings, Realtime fetchers must have < 1ms execution time and be infallible with no I/O operations.

Proposed fix
 fn zoned_times(opts: &Options) -> Vec<(String, Option<DateTime<FixedOffset>>)> {
+    let now = Utc::now();
     opts.timezones
         .as_deref()
         .unwrap_or(&[])
         .iter()
-        .map(|name| (name.clone(), resolve(name)))
+        .map(|name| (name.clone(), resolve(&now, name)))
         .collect()
 }
 
-fn resolve(name: &str) -> Option<DateTime<FixedOffset>> {
+fn resolve(now: &DateTime<Utc>, name: &str) -> Option<DateTime<FixedOffset>> {
     let tz: chrono_tz::Tz = name.parse().ok()?;
-    Some(Utc::now().with_timezone(&tz).fixed_offset())
+    Some(now.with_timezone(&tz).fixed_offset())
 }

Update the tests to pass a captured Utc::now() into resolve().

📝 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 zoned_times(opts: &Options) -> Vec<(String, Option<DateTime<FixedOffset>>)> {
opts.timezones
.as_deref()
.unwrap_or(&[])
.iter()
.map(|name| (name.clone(), resolve(name)))
.collect()
}
fn resolve(name: &str) -> Option<DateTime<FixedOffset>> {
let tz: chrono_tz::Tz = name.parse().ok()?;
Some(Utc::now().with_timezone(&tz).fixed_offset())
}
fn zoned_times(opts: &Options) -> Vec<(String, Option<DateTime<FixedOffset>>)> {
let now = Utc::now();
opts.timezones
.as_deref()
.unwrap_or(&[])
.iter()
.map(|name| (name.clone(), resolve(&now, name)))
.collect()
}
fn resolve(now: &DateTime<Utc>, name: &str) -> Option<DateTime<FixedOffset>> {
let tz: chrono_tz::Tz = name.parse().ok()?;
Some(now.with_timezone(&tz).fixed_offset())
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/clock/timezones.rs` around lines 36 - 48, The zoned_times()
function should capture Utc::now() once and reuse that instant for every
timezone instead of calling Utc::now() inside resolve() per-iteration; change
resolve(name: &str) -> Option<DateTime<FixedOffset>> to accept the instant
(e.g., resolve(name: &str, instant: DateTime<Utc>)) and have zoned_times() call
let now = Utc::now(); then map each timezone to (name.clone(), resolve(name,
now)); ensure resolve projects the provided instant into the zone with
with_timezone(&tz).fixed_offset(), and update any tests to pass the captured
instant accordingly to keep the realtime path infallible and fast.

Comment thread src/fetcher/mod.rs
Comment on lines +56 to +58
/// Fetcher-specific options passed through from `[widget.options]`. Each fetcher
/// deserializes its own typed view; unknown keys are ignored.
pub options: Option<toml::Value>,

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

Doc contradicts actual behavior — options with unknown keys is rejected, not ignored.

The comment says "unknown keys are ignored", but the only current consumer (clock's Options in src/fetcher/clock/options.rs) is annotated with #[serde(deny_unknown_fields)], so a typo in [widget.options] surfaces as a parse error and renders a shape-mismatch / error placeholder. Either drop the "ignored" claim here (and in src/config.rs Lines 48–52 which carries the same misleading note) or state that each fetcher chooses strict-vs-lenient on its own.

📝 Suggested doc tweak
-    /// Fetcher-specific options passed through from `[widget.options]`. Each fetcher
-    /// deserializes its own typed view; unknown keys are ignored.
+    /// Fetcher-specific options passed through from `[widget.options]`. Each fetcher
+    /// deserializes its own typed view and decides how strict to be about unknown keys
+    /// (the clock fetcher, for example, uses `deny_unknown_fields`).
     pub options: Option<toml::Value>,
📝 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
/// Fetcher-specific options passed through from `[widget.options]`. Each fetcher
/// deserializes its own typed view; unknown keys are ignored.
pub options: Option<toml::Value>,
/// Fetcher-specific options passed through from `[widget.options]`. Each fetcher
/// deserializes its own typed view and decides how strict to be about unknown keys
/// (the clock fetcher, for example, uses `deny_unknown_fields`).
pub options: Option<toml::Value>,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/mod.rs` around lines 56 - 58, The field `pub options:
Option<toml::Value>` in src/fetcher/mod.rs currently has a doc comment claiming
"unknown keys are ignored", but concrete consumers like the clock `Options` in
src/fetcher/clock/options.rs use `#[serde(deny_unknown_fields)]` so unknown keys
are rejected; update the doc for `options` to remove the incorrect "ignored"
claim and instead state that each fetcher decides strict vs lenient
deserialization (or explicitly note that some fetchers may deny unknown fields),
and make the same corresponding wording change in the similar note in
src/config.rs so docs match actual behavior and callers like the clock `Options`
using `deny_unknown_fields` are accurately described.

@unhappychoice unhappychoice changed the title feat(fetcher): expand clock with multi-mode options feat(fetcher): split clock into clock_* sibling fetchers Apr 22, 2026
Adds a generic `options: Option<toml::Value>` on WidgetConfig and
FetchContext so fetchers can read typed `[widget.options]` sub-tables.

Splits temporal features into sibling fetchers under a `clock_*` prefix
instead of one fat fetcher with mode dispatch:

- `clock` — base (Lines / Entries / Calendar), `timezone` / `events`
- `clock_timezones` — world-clock strip
- `clock_countdown` — target / targets
- `clock_ratio` — day / year / month / week / quarter / hour fraction
- `clock_state` — business_hours / weekend / night badge
- `clock_sunrise` — NOAA approximation from lat/lon
- `clock_derived` — moon_phase / zodiac / iso_week / 六曜 / ... (Lines)

Each has a narrow `Options` struct with `deny_unknown_fields` so invalid
keys surface as placeholders instead of silent wrong renders. Shared
primitives (tz resolution, safe strftime, julian day) live in
`clock/common.rs`.

Refs #41.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
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