diff --git a/README.md b/README.md index d16f5d5..eef5545 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,22 @@ cargo tauri build `src-tauri/target/release/` 以下に配布用バイナリが生成されます。 +### 日付時刻ライブラリと依存監査 + +日時処理は、RUSTSEC-2026-0543で保守停止が告知されたChronoではなくJiff 1.xを使用します。 +日常のローカル時刻、UTC表示、アラームの暦日計算はJiffが担当します。夏時間の重複時刻は +早い方、存在しない時刻は後の有効な時刻へ解決します。保存済みアラームJSONの形式は変更しません。 + +```bash +cd src-tauri +cargo tree --locked -i chrono # active dependencyは表示されないこと +cargo audit --deny warnings +``` + +Tauriが利用するcrateの非有効なoptional dependencyとして、`Cargo.lock`にChronoが残る場合があります。 +`cargo tree`でactive dependencyではないことを確認してください。`cargo audit`はlockfile単位で検査するため、 +この非有効なentryもRUSTSEC-2026-0543として報告します。 + ## ライセンス MIT License. 詳細は `LICENSE` を参照してください。 diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index cb73e40..3ebd59c 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -545,10 +545,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118" dependencies = [ "iana-time-zone", - "js-sys", "num-traits", "serde", - "wasm-bindgen", "windows-link 0.2.1", ] @@ -1907,6 +1905,58 @@ dependencies = [ "system-deps", ] +[[package]] +name = "jiff" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5d126d72eb017f10b302e73bdeca446bea405ee449af4d9e7866d6b082d83e" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link 0.2.1", +] + +[[package]] +name = "jiff-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0127e9bde3c6130d6169e7d8d68676e4be69c4bf7573c308b6f960a5089c428" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + +[[package]] +name = "jiff-tzdb-platform" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jni" version = "0.21.1" @@ -2779,6 +2829,21 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.4" @@ -3669,6 +3734,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -3769,8 +3845,8 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" name = "tauclock" version = "0.1.0" dependencies = [ - "chrono", "dirs 5.0.1", + "jiff", "log", "serde", "serde_json", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index c31a293..1283a1c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -22,7 +22,7 @@ tauri = { version = "2", features = [] } tauri-plugin-opener = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" -chrono = "0.4.42" +jiff = "1" tauri-plugin-log = "2" uuid = { version = "1", features = ["v4"] } dirs = "5" diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 95fda6b..a502f50 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -1,7 +1,4 @@ -use chrono::{ - DateTime, Datelike, Days, Local, LocalResult, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, - Timelike, Utc, -}; +use jiff::{tz::TimeZone, Timestamp, ZonedDateTime}; use log::{debug, error, info, trace, warn}; use serde::{Deserialize, Serialize}; use std::{ @@ -24,14 +21,21 @@ const TIMER_MIN_MS: u64 = 1000; pub struct AppState { inner: Mutex, storage_path: PathBuf, + time_zone: TimeZone, } impl AppState { /// Constructs a new state container and eagerly loads persisted alarms. pub fn new(storage_path: PathBuf) -> Self { + Self::with_time_zone(storage_path, TimeZone::system()) + } + + /// Constructs state using an explicit time zone. Production passes the + /// operating system zone; tests can provide a named IANA zone. + fn with_time_zone(storage_path: PathBuf, time_zone: TimeZone) -> Self { let mut inner = StateInner::default(); if let Some(list) = load_alarms(&storage_path) { - let now = Local::now(); + let now = now_in_time_zone(&time_zone); inner.alarms = list .into_iter() .map(|alarm| Alarm { @@ -48,6 +52,7 @@ impl AppState { Self { inner: Mutex::new(inner), storage_path, + time_zone, } } @@ -116,15 +121,15 @@ impl AppState { /// snapshot generation, and persistence side effects. fn apply(&self, mutator: F) -> FrontendState where - F: FnOnce(&mut StateInner, i64, &DateTime), + F: FnOnce(&mut StateInner, i64, &ZonedDateTime), { - let now_local = Local::now(); - let now_ms = now_local.timestamp_millis(); + let now_local = now_in_time_zone(&self.time_zone); + let now_ms = now_local.timestamp().as_millisecond(); let mut guard = self.inner.lock().expect("state mutex poisoned"); trace!("Running state mutation (now_ms={})", now_ms); mutator(&mut guard, now_ms, &now_local); guard.refresh(now_ms, &now_local); - let snapshot = guard.to_frontend(&now_local); + let snapshot = guard.build_frontend(&now_local); let persisted = if guard.alarms_dirty { Some( guard @@ -194,16 +199,16 @@ struct StateInner { impl StateInner { /// Executes periodic tasks that should run on every mutation or tick. - fn refresh(&mut self, now_ms: i64, now_local: &DateTime) { + fn refresh(&mut self, now_ms: i64, now_local: &ZonedDateTime) { self.process_alarms(now_ms, now_local); self.update_timer(now_ms); self.expire_status(now_ms); } /// Builds a full [`FrontendState`] representation of the current data. - fn to_frontend(&mut self, now_local: &DateTime) -> FrontendState { - let now_ms = now_local.timestamp_millis(); - let now_utc = now_local.with_timezone(&Utc); + fn build_frontend(&mut self, now_local: &ZonedDateTime) -> FrontendState { + let now_ms = now_local.timestamp().as_millisecond(); + let now_utc = now_local.timestamp().to_zoned_datetime(TimeZone::UTC); let clock = ClockState { local_time: format_time(now_local.hour(), now_local.minute(), now_local.second()), local_date: format_date(now_local.year(), now_local.month(), now_local.day()), @@ -231,7 +236,7 @@ impl StateInner { raw_time: &str, label: Option<&str>, now_ms: i64, - now_local: &DateTime, + now_local: &ZonedDateTime, ) { let Some((hour, minute)) = parse_alarm_time(raw_time) else { warn!("Invalid alarm time input: {}", raw_time); @@ -261,7 +266,7 @@ impl StateInner { } /// Toggles an alarm's active state and recalculates its next trigger. - fn toggle_alarm(&mut self, id: &str, now_local: &DateTime) { + fn toggle_alarm(&mut self, id: &str, now_local: &ZonedDateTime) { if let Some(alarm) = self.alarms.iter_mut().find(|alarm| alarm.id == id) { alarm.active = !alarm.active; alarm.ringing_until = None; @@ -412,7 +417,7 @@ impl StateInner { /// Iterates configured alarms, triggering those scheduled for the current /// tick and scheduling their next activation. - fn process_alarms(&mut self, now_ms: i64, now_local: &DateTime) { + fn process_alarms(&mut self, now_ms: i64, now_local: &ZonedDateTime) { let mut triggered_labels = Vec::new(); for alarm in &mut self.alarms { if let Some(until) = alarm.ringing_until { @@ -512,9 +517,7 @@ impl StateInner { /// Builds the timer view model by formatting durations and button labels. fn build_timer_view(&self) -> TimerView { - let display_ms = if self.timer.running { - self.timer.remaining_ms - } else if self.timer.remaining_ms > 0 { + let display_ms = if self.timer.remaining_ms > 0 { self.timer.remaining_ms } else { self.timer.initial_ms @@ -733,12 +736,12 @@ fn load_alarms(path: &Path) -> Option> { } /// Formats a timestamp as HH:MM:SS. -fn format_time(hour: u32, minute: u32, second: u32) -> String { +fn format_time(hour: i8, minute: i8, second: i8) -> String { format!("{:02}:{:02}:{:02}", hour, minute, second) } /// Formats a date as YYYY-MM-DD. -fn format_date(year: i32, month: u32, day: u32) -> String { +fn format_date(year: i16, month: i8, day: i8) -> String { format!("{year:04}-{month:02}-{day:02}") } @@ -768,7 +771,7 @@ fn format_relative(target_ms: i64, now_ms: i64) -> String { /// Formats a duration for timer display, switching to HH:MM:SS when needed. fn format_duration(ms: u64) -> String { - let total_seconds = (ms / 1000) as u64; + let total_seconds = ms / 1000; let minutes = total_seconds / 60; let seconds = total_seconds % 60; let hundredths = (ms % 1000) / 10; @@ -870,27 +873,122 @@ fn parse_unit_duration(value: &str) -> Option { } } -/// Calculates the next trigger timestamp in milliseconds for an alarm. -fn resolve_next_trigger(hour: u8, minute: u8, now_local: &DateTime) -> i64 { - let naive_time = NaiveTime::from_hms_opt(hour as u32, minute as u32, 0) - .unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap()); - let mut candidate = combine_local(now_local.date_naive(), naive_time); - if candidate.timestamp_millis() <= now_local.timestamp_millis() { - let next_day = now_local.date_naive() + Days::new(1); - candidate = combine_local(next_day, naive_time); - } - candidate.timestamp_millis() +/// Returns the current system instant expressed in the requested zone. +fn now_in_time_zone(time_zone: &TimeZone) -> ZonedDateTime { + Timestamp::now().to_zoned_datetime(time_zone.clone()) } -/// Safely combines a date and time within the Local timezone, falling back to -/// UTC if the local conversion is ambiguous or invalid. -fn combine_local(date: NaiveDate, time: NaiveTime) -> DateTime { - let naive = NaiveDateTime::new(date, time); - match Local.from_local_datetime(&naive) { - LocalResult::Single(value) => value, - LocalResult::Ambiguous(first, _second) => first, - LocalResult::None => { - DateTime::::from_naive_utc_and_offset(naive, Utc).with_timezone(&Local) - } +/// Calculates the next trigger timestamp in milliseconds for an alarm. Jiff's +/// compatible resolution chooses the earlier instant in a fold and the later +/// valid wall time in a gap. +fn resolve_next_trigger(hour: u8, minute: u8, now_local: &ZonedDateTime) -> i64 { + let time_zone = now_local.time_zone().clone(); + let mut candidate = now_local + .date() + .at(hour as i8, minute as i8, 0, 0) + .to_zoned_datetime(time_zone.clone()) + .expect("alarm date is representable"); + if candidate.timestamp().as_millisecond() <= now_local.timestamp().as_millisecond() { + candidate = now_local + .date() + .tomorrow() + .expect("tomorrow is representable") + .at(hour as i8, minute as i8, 0, 0) + .to_zoned_datetime(time_zone) + .expect("next alarm date is representable"); + } + candidate.timestamp().as_millisecond() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn named_zone(name: &str) -> TimeZone { + TimeZone::get(name).expect("named test time zone is available") + } + + fn zoned(instant: &str, time_zone: TimeZone) -> ZonedDateTime { + instant + .parse::() + .expect("valid test instant") + .to_zoned_datetime(time_zone) + } + + fn milliseconds(instant: &str) -> i64 { + instant + .parse::() + .expect("valid expected instant") + .as_millisecond() + } + + #[test] + fn formats_clock_labels_without_changing_the_ui_contract() { + assert_eq!(format_date(2026, 11, 20), "2026-11-20"); + assert_eq!(format_time(7, 5, 9), "07:05:09"); + } + + #[test] + fn production_state_can_be_configured_with_a_named_test_zone() { + let app = AppState::with_time_zone( + PathBuf::from("missing-test-alarms.json"), + named_zone("Asia/Tokyo"), + ); + assert_eq!(app.time_zone.iana_name(), Some("Asia/Tokyo")); + } + + #[test] + fn schedules_later_today_and_equal_time_tomorrow() { + let utc = named_zone("UTC"); + let now = zoned("2024-01-15T09:30:00Z", utc.clone()); + assert_eq!( + resolve_next_trigger(9, 31, &now), + milliseconds("2024-01-15T09:31:00Z") + ); + assert_eq!( + resolve_next_trigger(9, 30, &now), + milliseconds("2024-01-16T09:30:00Z") + ); + } + + #[test] + fn new_york_fold_uses_the_earlier_occurrence() { + let new_york = named_zone("America/New_York"); + let now = zoned("2024-11-03T00:00:00Z", new_york); + assert_eq!( + resolve_next_trigger(1, 30, &now), + milliseconds("2024-11-03T05:30:00Z") + ); + } + + #[test] + fn new_york_gap_uses_jiff_compatible_later_time() { + let new_york = named_zone("America/New_York"); + let now = zoned("2024-03-10T00:00:00Z", new_york); + assert_eq!( + resolve_next_trigger(2, 30, &now), + milliseconds("2024-03-10T07:30:00Z") + ); + } + + #[test] + fn next_alarm_advances_by_calendar_day_across_dst() { + let new_york = named_zone("America/New_York"); + let now = zoned("2024-03-09T08:30:01Z", new_york); + let trigger = resolve_next_trigger(3, 30, &now); + assert_eq!(trigger, milliseconds("2024-03-10T07:30:00Z")); + assert_eq!(trigger - now.timestamp().as_millisecond(), 82_799_000); + } + + #[test] + fn persisted_alarm_json_round_trips_without_schedule_fields() { + let json = + r#"{"alarms":[{"id":"wake","hour":7,"minute":30,"label":"Wake up","active":true}]}"#; + let store: AlarmStore = serde_json::from_str(json).expect("stored alarm JSON parses"); + assert_eq!(store.alarms.len(), 1); + assert_eq!(store.alarms[0].id, "wake"); + assert_eq!(store.alarms[0].hour, 7); + assert_eq!(store.alarms[0].minute, 30); + assert_eq!(serde_json::to_string(&store).unwrap(), json); } }