Skip to main content

aoc_toolkit/application/progress/
stars.rs

1use std::fs;
2use std::io::ErrorKind;
3use std::num::NonZeroU64;
4use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7
8use crate::ClientError;
9use crate::application::calendar::CalendarDate;
10use crate::client::cache;
11
12const SCHEMA_VERSION: u32 = 1;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum VerifiedStar {
16    Unknown,
17    Missing,
18    Earned,
19}
20
21#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
22#[serde(deny_unknown_fields)]
23pub struct StarSnapshot {
24    schema_version: u32,
25    year: usize,
26    synced_at_unix_seconds: u64,
27    stars_by_day: Vec<u8>,
28}
29
30impl StarSnapshot {
31    /// Creates a snapshot for consecutive days starting with day one.
32    ///
33    /// # Errors
34    ///
35    /// Returns an error if the edition or star counts are invalid.
36    pub fn new(
37        year: usize,
38        synced_at_unix_seconds: u64,
39        stars_by_day: Vec<u8>,
40    ) -> Result<Self, StarStoreError> {
41        let snapshot = Self {
42            schema_version: SCHEMA_VERSION,
43            year,
44            synced_at_unix_seconds,
45            stars_by_day,
46        };
47        snapshot.validate(year)?;
48        Ok(snapshot)
49    }
50
51    pub(super) fn year(&self) -> usize {
52        self.year
53    }
54
55    #[must_use]
56    pub fn synced_at_unix_seconds(&self) -> u64 {
57        self.synced_at_unix_seconds
58    }
59
60    #[must_use]
61    pub fn star(&self, day: usize, part: u8) -> VerifiedStar {
62        if !(1..=2).contains(&part) {
63            return VerifiedStar::Unknown;
64        }
65
66        let Some(count) = day
67            .checked_sub(1)
68            .and_then(|index| self.stars_by_day.get(index))
69        else {
70            return VerifiedStar::Unknown;
71        };
72
73        if part <= *count {
74            VerifiedStar::Earned
75        } else {
76            VerifiedStar::Missing
77        }
78    }
79
80    fn validate(&self, year: usize) -> Result<(), StarStoreError> {
81        if self.schema_version != SCHEMA_VERSION {
82            return Err(StarStoreError::UnsupportedVersion(self.schema_version));
83        }
84
85        if self.year != year
86            || !(2015..=9999).contains(&year)
87            || self.stars_by_day.len() > CalendarDate::edition_days(year)
88            || self.stars_by_day.iter().any(|&count| count > 2)
89        {
90            return Err(StarStoreError::InvalidSnapshot);
91        }
92
93        Ok(())
94    }
95}
96
97pub struct StarStore {
98    root: PathBuf,
99}
100
101#[derive(Debug, thiserror::Error)]
102pub enum StarStoreError {
103    #[error(transparent)]
104    Cache(#[from] ClientError),
105
106    #[error("Cannot read star snapshot at {path}: {source}")]
107    Read {
108        path: PathBuf,
109        #[source]
110        source: std::io::Error,
111    },
112
113    #[error("Invalid star snapshot JSON: {0}")]
114    Json(#[from] serde_json::Error),
115
116    #[error("Unsupported star snapshot schema version: {0}")]
117    UnsupportedVersion(u32),
118
119    #[error("Invalid star snapshot edition or star counts")]
120    InvalidSnapshot,
121}
122
123impl StarStore {
124    /// Opens the global star snapshot store.
125    ///
126    /// # Errors
127    ///
128    /// Returns an error if the toolkit cache directory cannot be resolved.
129    pub fn global() -> Result<Self, StarStoreError> {
130        Ok(Self::at_cache_root(&cache::root()?))
131    }
132
133    pub(super) fn at_cache_root(root: &Path) -> Self {
134        Self {
135            root: root.join("stars"),
136        }
137    }
138
139    /// Loads the last successful snapshot for an account and edition.
140    ///
141    /// # Errors
142    ///
143    /// Returns an error if an existing snapshot cannot be read or validated.
144    pub fn load(
145        &self,
146        account_id: NonZeroU64,
147        year: usize,
148    ) -> Result<Option<StarSnapshot>, StarStoreError> {
149        #[derive(Deserialize)]
150        struct Header {
151            schema_version: u32,
152        }
153
154        let path = self.snapshot_path(account_id, year);
155        let bytes = match fs::read(&path) {
156            Ok(bytes) => bytes,
157            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
158            Err(source) => return Err(StarStoreError::Read { path, source }),
159        };
160
161        let header: Header = serde_json::from_slice(&bytes)?;
162        if header.schema_version != SCHEMA_VERSION {
163            return Err(StarStoreError::UnsupportedVersion(header.schema_version));
164        }
165
166        let snapshot: StarSnapshot = serde_json::from_slice(&bytes)?;
167        snapshot.validate(year)?;
168        Ok(Some(snapshot))
169    }
170
171    /// Atomically replaces the stored snapshot for a verified account and edition.
172    ///
173    /// # Errors
174    ///
175    /// Returns an error if the snapshot cannot be validated, encoded, or saved.
176    pub fn save(
177        &self,
178        account_id: NonZeroU64,
179        snapshot: &StarSnapshot,
180    ) -> Result<(), StarStoreError> {
181        snapshot.validate(snapshot.year)?;
182        let json = serde_json::to_string_pretty(snapshot)?;
183        cache::store(&self.snapshot_path(account_id, snapshot.year), &json)?;
184        Ok(())
185    }
186
187    pub(super) fn snapshot_path(&self, account_id: NonZeroU64, year: usize) -> PathBuf {
188        Path::new(&self.root)
189            .join(account_id.to_string())
190            .join(format!("{year}.json"))
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use std::fs;
197    use std::num::NonZeroU64;
198
199    use tempfile::tempdir;
200
201    use super::{StarSnapshot, StarStore, StarStoreError, VerifiedStar};
202
203    #[test]
204    fn distinguishes_earned_missing_and_unknown_stars() {
205        let snapshot = StarSnapshot::new(2025, 100, vec![2, 0, 1]).unwrap();
206
207        assert_eq!(snapshot.star(1, 2), VerifiedStar::Earned);
208        assert_eq!(snapshot.star(2, 1), VerifiedStar::Missing);
209        assert_eq!(snapshot.star(3, 1), VerifiedStar::Earned);
210        assert_eq!(snapshot.star(3, 2), VerifiedStar::Missing);
211        assert_eq!(snapshot.star(4, 1), VerifiedStar::Unknown);
212        assert_eq!(snapshot.synced_at_unix_seconds(), 100);
213    }
214
215    #[test]
216    fn keeps_snapshots_isolated_when_switching_accounts() {
217        let directory = tempdir().unwrap();
218        let store = StarStore {
219            root: directory.path().join("stars"),
220        };
221        let first = NonZeroU64::new(123).unwrap();
222        let second = NonZeroU64::new(456).unwrap();
223
224        let first_snapshot = StarSnapshot::new(2025, 100, vec![2]).unwrap();
225        store.save(first, &first_snapshot).unwrap();
226
227        assert_eq!(store.load(second, 2025).unwrap(), None);
228        assert_eq!(store.load(first, 2024).unwrap(), None);
229
230        let second_snapshot = StarSnapshot::new(2025, 200, vec![0]).unwrap();
231        store.save(second, &second_snapshot).unwrap();
232
233        assert_eq!(store.load(second, 2025).unwrap(), Some(second_snapshot));
234        assert_eq!(store.load(first, 2025).unwrap(), Some(first_snapshot));
235    }
236
237    #[test]
238    fn validates_edition_lengths_and_star_counts() {
239        assert!(StarSnapshot::new(2024, 100, vec![0; 25]).is_ok());
240        assert!(matches!(
241            StarSnapshot::new(2025, 100, vec![0; 13]),
242            Err(StarStoreError::InvalidSnapshot),
243        ));
244        assert!(matches!(
245            StarSnapshot::new(2025, 100, vec![3]),
246            Err(StarStoreError::InvalidSnapshot),
247        ));
248    }
249
250    #[test]
251    fn rejects_unknown_snapshot_versions() {
252        let directory = tempdir().unwrap();
253        let store = StarStore {
254            root: directory.path().join("stars"),
255        };
256        let account = NonZeroU64::new(123).unwrap();
257        let path = store.snapshot_path(account, 2025);
258
259        fs::create_dir_all(path.parent().unwrap()).unwrap();
260        fs::write(path, br#"{"schema_version":2}"#).unwrap();
261
262        assert!(matches!(
263            store.load(account, 2025),
264            Err(StarStoreError::UnsupportedVersion(2)),
265        ));
266    }
267}