use std::fs;
use std::io::ErrorKind;
use std::num::NonZeroU64;
use chrono::Utc;
use super::{CalendarHtmlError, StarSnapshot, StarStore, StarStoreError};
use crate::ClientError;
use crate::application::calendar::CalendarDate;
use crate::client::cache;
use crate::client::http::AocHttpClient;
use crate::client::session::{SessionStore, resolve_session};
const SYNC_INTERVAL_SECONDS: u64 = 15 * 60;
#[derive(Debug)]
pub enum StarSyncOutcome {
Refreshed(StarSnapshot),
Cached(StarSnapshot),
}
#[derive(Debug, thiserror::Error)]
pub enum StarSyncError {
#[error("No puzzles are unlocked for Advent of Code {0}")]
NoUnlockedPuzzles(usize),
#[error("Cannot determine the current Unix timestamp")]
InvalidClock,
#[error("Invalid last calendar sync attempt timestamp")]
InvalidAttemptTimestamp,
#[error("Calendar sync is temporarily throttled and no snapshot is available")]
Throttled,
#[error(transparent)]
Client(#[from] ClientError),
#[error(transparent)]
Calendar(#[from] CalendarHtmlError),
#[error(transparent)]
Store(#[from] StarStoreError),
}
pub fn sync_stars(year: usize) -> Result<StarSyncOutcome, StarSyncError> {
let unlocked_days = CalendarDate::today().unlocked_days(year);
if unlocked_days == 0 {
return Err(StarSyncError::NoUnlockedPuzzles(year));
}
let (session, _) = resolve_session()?.ok_or(ClientError::MissingSession)?;
let root = cache::root()?;
let contact = match std::env::var("AOC_TOOLKIT_CONTACT") {
Ok(value) => Some(value),
Err(std::env::VarError::NotPresent) => None,
Err(std::env::VarError::NotUnicode(_)) => {
return Err(ClientError::InvalidSyncContact.into());
}
};
let client = AocHttpClient::for_star_sync(contact.as_deref())?;
let account_id = if let Some(account_id) = SessionStore::known_account(&root, &session)? {
account_id
} else {
let account_id = client.verify_session_at(&root, &session)?;
SessionStore::remember_account_at(&root, &session, account_id)?;
account_id
};
let account_id = NonZeroU64::new(account_id).ok_or(ClientError::AccountIdentityUnavailable)?;
let store = StarStore::at_cache_root(&root);
sync_snapshot(&store, account_id, year, unix_timestamp()?, || {
let document = client.fetch_calendar_at(&root, year, &session)?;
Ok(StarSnapshot::from_calendar_html(
&document,
year,
unlocked_days,
unix_timestamp()?,
)?)
})
}
pub fn cached_stars(year: usize) -> Result<Option<StarSnapshot>, StarSyncError> {
let Some((session, _)) = resolve_session()? else {
return Ok(None);
};
let root = cache::root()?;
let Some(account_id) = SessionStore::known_account(&root, &session)? else {
return Ok(None);
};
let account_id = NonZeroU64::new(account_id).ok_or(ClientError::AccountIdentityUnavailable)?;
Ok(StarStore::at_cache_root(&root).load(account_id, year)?)
}
fn unix_timestamp() -> Result<u64, StarSyncError> {
u64::try_from(Utc::now().timestamp()).map_err(|_| StarSyncError::InvalidClock)
}
fn sync_snapshot(
store: &StarStore,
account_id: NonZeroU64,
year: usize,
now: u64,
fetch: impl FnOnce() -> Result<StarSnapshot, StarSyncError>,
) -> Result<StarSyncOutcome, StarSyncError> {
let path = store.snapshot_path(account_id, year);
let attempt_path = path.with_extension("attempt");
let _guard = cache::lock(&path.with_extension("sync.lock"))?;
match fs::read_to_string(&attempt_path) {
Ok(value) => {
let last_attempt = value
.trim()
.parse::<u64>()
.map_err(|_| StarSyncError::InvalidAttemptTimestamp)?;
if now.saturating_sub(last_attempt) < SYNC_INTERVAL_SECONDS {
return store
.load(account_id, year)?
.map(StarSyncOutcome::Cached)
.ok_or(StarSyncError::Throttled);
}
}
Err(error) if error.kind() == ErrorKind::NotFound => {}
Err(source) => {
return Err(StarStoreError::Read {
path: attempt_path,
source,
}
.into());
}
}
cache::store(&attempt_path, &now.to_string())?;
let snapshot = fetch()?;
store.save(account_id, &snapshot)?;
Ok(StarSyncOutcome::Refreshed(snapshot))
}
#[cfg(test)]
mod tests {
use std::num::NonZeroU64;
use tempfile::tempdir;
use super::{StarSyncError, StarSyncOutcome, sync_snapshot};
use crate::ClientError;
use crate::application::progress::{StarSnapshot, StarStore, VerifiedStar};
#[test]
fn reuses_the_snapshot_during_the_refresh_interval() {
let root = tempdir().unwrap();
let store = StarStore::at_cache_root(root.path());
let account = NonZeroU64::new(123).unwrap();
let outcome = sync_snapshot(&store, account, 2025, 1_000, || {
Ok(StarSnapshot::new(2025, 1_000, vec![1]).unwrap())
})
.unwrap();
assert!(matches!(outcome, StarSyncOutcome::Refreshed(_)));
let outcome = sync_snapshot(&store, account, 2025, 1_899, || {
panic!("Throttled sync must not fetch the calendar");
})
.unwrap();
let StarSyncOutcome::Cached(snapshot) = outcome else {
panic!("Expected a cached snapshot");
};
assert_eq!(snapshot.star(1, 1), VerifiedStar::Earned);
assert_eq!(snapshot.synced_at_unix_seconds(), 1_000);
}
#[test]
fn failed_refresh_preserves_the_snapshot_and_throttles_retries() {
let root = tempdir().unwrap();
let store = StarStore::at_cache_root(root.path());
let account = NonZeroU64::new(123).unwrap();
let previous = StarSnapshot::new(2025, 1_000, vec![2]).unwrap();
store.save(account, &previous).unwrap();
let result = sync_snapshot(&store, account, 2025, 1_900, || {
Err(ClientError::RateLimited.into())
});
assert!(matches!(
result,
Err(StarSyncError::Client(ClientError::RateLimited)),
));
assert_eq!(store.load(account, 2025).unwrap(), Some(previous));
let result = sync_snapshot(&store, account, 2025, 1_901, || {
panic!("A failed request must still throttle retries");
});
assert!(matches!(result, Ok(StarSyncOutcome::Cached(_))));
}
}