Skip to main content

aoc_toolkit/application/progress/
sync.rs

1use std::fs;
2use std::io::ErrorKind;
3use std::num::NonZeroU64;
4
5use chrono::Utc;
6
7use super::{CalendarHtmlError, StarSnapshot, StarStore, StarStoreError};
8use crate::ClientError;
9use crate::application::calendar::CalendarDate;
10use crate::client::cache;
11use crate::client::http::AocHttpClient;
12use crate::client::session::{SessionStore, resolve_session};
13
14const SYNC_INTERVAL_SECONDS: u64 = 15 * 60;
15
16#[derive(Debug)]
17pub enum StarSyncOutcome {
18    Refreshed(StarSnapshot),
19    Cached(StarSnapshot),
20}
21
22#[derive(Debug, thiserror::Error)]
23pub enum StarSyncError {
24    #[error("No puzzles are unlocked for Advent of Code {0}")]
25    NoUnlockedPuzzles(usize),
26
27    #[error("Cannot determine the current Unix timestamp")]
28    InvalidClock,
29
30    #[error("Invalid last calendar sync attempt timestamp")]
31    InvalidAttemptTimestamp,
32
33    #[error("Calendar sync is temporarily throttled and no snapshot is available")]
34    Throttled,
35
36    #[error(transparent)]
37    Client(#[from] ClientError),
38
39    #[error(transparent)]
40    Calendar(#[from] CalendarHtmlError),
41
42    #[error(transparent)]
43    Store(#[from] StarStoreError),
44}
45
46/// Refreshes verified stars for the effective account and selected edition.
47///
48/// A recent attempt can return the previously saved snapshot without a
49/// calendar request.
50///
51/// # Errors
52///
53/// Returns an error if the session, calendar, or snapshot cannot be verified,
54/// or if a refresh is throttled and no cached snapshot is available.
55pub fn sync_stars(year: usize) -> Result<StarSyncOutcome, StarSyncError> {
56    let unlocked_days = CalendarDate::today().unlocked_days(year);
57    if unlocked_days == 0 {
58        return Err(StarSyncError::NoUnlockedPuzzles(year));
59    }
60
61    let (session, _) = resolve_session()?.ok_or(ClientError::MissingSession)?;
62    let root = cache::root()?;
63    let contact = match std::env::var("AOC_TOOLKIT_CONTACT") {
64        Ok(value) => Some(value),
65        Err(std::env::VarError::NotPresent) => None,
66        Err(std::env::VarError::NotUnicode(_)) => {
67            return Err(ClientError::InvalidSyncContact.into());
68        }
69    };
70    let client = AocHttpClient::for_star_sync(contact.as_deref())?;
71    let account_id = if let Some(account_id) = SessionStore::known_account(&root, &session)? {
72        account_id
73    } else {
74        let account_id = client.verify_session_at(&root, &session)?;
75        SessionStore::remember_account_at(&root, &session, account_id)?;
76        account_id
77    };
78    let account_id = NonZeroU64::new(account_id).ok_or(ClientError::AccountIdentityUnavailable)?;
79    let store = StarStore::at_cache_root(&root);
80
81    sync_snapshot(&store, account_id, year, unix_timestamp()?, || {
82        let document = client.fetch_calendar_at(&root, year, &session)?;
83        Ok(StarSnapshot::from_calendar_html(
84            &document,
85            year,
86            unlocked_days,
87            unix_timestamp()?,
88        )?)
89    })
90}
91
92/// Loads the saved snapshot for the effective account without network access.
93///
94/// A missing session or an unknown local account binding returns no snapshot.
95///
96/// # Errors
97///
98/// Returns an error if session resolution, the account binding, or the
99/// stored snapshot cannot be read.
100pub fn cached_stars(year: usize) -> Result<Option<StarSnapshot>, StarSyncError> {
101    let Some((session, _)) = resolve_session()? else {
102        return Ok(None);
103    };
104
105    let root = cache::root()?;
106    let Some(account_id) = SessionStore::known_account(&root, &session)? else {
107        return Ok(None);
108    };
109    let account_id = NonZeroU64::new(account_id).ok_or(ClientError::AccountIdentityUnavailable)?;
110
111    Ok(StarStore::at_cache_root(&root).load(account_id, year)?)
112}
113
114fn unix_timestamp() -> Result<u64, StarSyncError> {
115    u64::try_from(Utc::now().timestamp()).map_err(|_| StarSyncError::InvalidClock)
116}
117
118fn sync_snapshot(
119    store: &StarStore,
120    account_id: NonZeroU64,
121    year: usize,
122    now: u64,
123    fetch: impl FnOnce() -> Result<StarSnapshot, StarSyncError>,
124) -> Result<StarSyncOutcome, StarSyncError> {
125    let path = store.snapshot_path(account_id, year);
126    let attempt_path = path.with_extension("attempt");
127    let _guard = cache::lock(&path.with_extension("sync.lock"))?;
128
129    match fs::read_to_string(&attempt_path) {
130        Ok(value) => {
131            let last_attempt = value
132                .trim()
133                .parse::<u64>()
134                .map_err(|_| StarSyncError::InvalidAttemptTimestamp)?;
135
136            if now.saturating_sub(last_attempt) < SYNC_INTERVAL_SECONDS {
137                return store
138                    .load(account_id, year)?
139                    .map(StarSyncOutcome::Cached)
140                    .ok_or(StarSyncError::Throttled);
141            }
142        }
143        Err(error) if error.kind() == ErrorKind::NotFound => {}
144        Err(source) => {
145            return Err(StarStoreError::Read {
146                path: attempt_path,
147                source,
148            }
149            .into());
150        }
151    }
152
153    cache::store(&attempt_path, &now.to_string())?;
154    let snapshot = fetch()?;
155    store.save(account_id, &snapshot)?;
156
157    Ok(StarSyncOutcome::Refreshed(snapshot))
158}
159
160#[cfg(test)]
161mod tests {
162    use std::num::NonZeroU64;
163
164    use tempfile::tempdir;
165
166    use super::{StarSyncError, StarSyncOutcome, sync_snapshot};
167    use crate::ClientError;
168    use crate::application::progress::{StarSnapshot, StarStore, VerifiedStar};
169
170    #[test]
171    fn reuses_the_snapshot_during_the_refresh_interval() {
172        let root = tempdir().unwrap();
173        let store = StarStore::at_cache_root(root.path());
174        let account = NonZeroU64::new(123).unwrap();
175
176        let outcome = sync_snapshot(&store, account, 2025, 1_000, || {
177            Ok(StarSnapshot::new(2025, 1_000, vec![1]).unwrap())
178        })
179        .unwrap();
180        assert!(matches!(outcome, StarSyncOutcome::Refreshed(_)));
181
182        let outcome = sync_snapshot(&store, account, 2025, 1_899, || {
183            panic!("Throttled sync must not fetch the calendar");
184        })
185        .unwrap();
186
187        let StarSyncOutcome::Cached(snapshot) = outcome else {
188            panic!("Expected a cached snapshot");
189        };
190        assert_eq!(snapshot.star(1, 1), VerifiedStar::Earned);
191        assert_eq!(snapshot.synced_at_unix_seconds(), 1_000);
192    }
193
194    #[test]
195    fn failed_refresh_preserves_the_snapshot_and_throttles_retries() {
196        let root = tempdir().unwrap();
197        let store = StarStore::at_cache_root(root.path());
198        let account = NonZeroU64::new(123).unwrap();
199
200        let previous = StarSnapshot::new(2025, 1_000, vec![2]).unwrap();
201        store.save(account, &previous).unwrap();
202
203        let result = sync_snapshot(&store, account, 2025, 1_900, || {
204            Err(ClientError::RateLimited.into())
205        });
206        assert!(matches!(
207            result,
208            Err(StarSyncError::Client(ClientError::RateLimited)),
209        ));
210        assert_eq!(store.load(account, 2025).unwrap(), Some(previous));
211
212        let result = sync_snapshot(&store, account, 2025, 1_901, || {
213            panic!("A failed request must still throttle retries");
214        });
215        assert!(matches!(result, Ok(StarSyncOutcome::Cached(_))));
216    }
217}