use std::fs;
use std::io::ErrorKind;
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::ClientError;
use crate::application::calendar::CalendarDate;
use crate::client::cache;
const SCHEMA_VERSION: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerifiedStar {
Unknown,
Missing,
Earned,
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct StarSnapshot {
schema_version: u32,
year: usize,
synced_at_unix_seconds: u64,
stars_by_day: Vec<u8>,
}
impl StarSnapshot {
pub fn new(
year: usize,
synced_at_unix_seconds: u64,
stars_by_day: Vec<u8>,
) -> Result<Self, StarStoreError> {
let snapshot = Self {
schema_version: SCHEMA_VERSION,
year,
synced_at_unix_seconds,
stars_by_day,
};
snapshot.validate(year)?;
Ok(snapshot)
}
pub(super) fn year(&self) -> usize {
self.year
}
#[must_use]
pub fn synced_at_unix_seconds(&self) -> u64 {
self.synced_at_unix_seconds
}
#[must_use]
pub fn star(&self, day: usize, part: u8) -> VerifiedStar {
if !(1..=2).contains(&part) {
return VerifiedStar::Unknown;
}
let Some(count) = day
.checked_sub(1)
.and_then(|index| self.stars_by_day.get(index))
else {
return VerifiedStar::Unknown;
};
if part <= *count {
VerifiedStar::Earned
} else {
VerifiedStar::Missing
}
}
fn validate(&self, year: usize) -> Result<(), StarStoreError> {
if self.schema_version != SCHEMA_VERSION {
return Err(StarStoreError::UnsupportedVersion(self.schema_version));
}
if self.year != year
|| !(2015..=9999).contains(&year)
|| self.stars_by_day.len() > CalendarDate::edition_days(year)
|| self.stars_by_day.iter().any(|&count| count > 2)
{
return Err(StarStoreError::InvalidSnapshot);
}
Ok(())
}
}
pub struct StarStore {
root: PathBuf,
}
#[derive(Debug, thiserror::Error)]
pub enum StarStoreError {
#[error(transparent)]
Cache(#[from] ClientError),
#[error("Cannot read star snapshot at {path}: {source}")]
Read {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("Invalid star snapshot JSON: {0}")]
Json(#[from] serde_json::Error),
#[error("Unsupported star snapshot schema version: {0}")]
UnsupportedVersion(u32),
#[error("Invalid star snapshot edition or star counts")]
InvalidSnapshot,
}
impl StarStore {
pub fn global() -> Result<Self, StarStoreError> {
Ok(Self::at_cache_root(&cache::root()?))
}
pub(super) fn at_cache_root(root: &Path) -> Self {
Self {
root: root.join("stars"),
}
}
pub fn load(
&self,
account_id: NonZeroU64,
year: usize,
) -> Result<Option<StarSnapshot>, StarStoreError> {
#[derive(Deserialize)]
struct Header {
schema_version: u32,
}
let path = self.snapshot_path(account_id, year);
let bytes = match fs::read(&path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
Err(source) => return Err(StarStoreError::Read { path, source }),
};
let header: Header = serde_json::from_slice(&bytes)?;
if header.schema_version != SCHEMA_VERSION {
return Err(StarStoreError::UnsupportedVersion(header.schema_version));
}
let snapshot: StarSnapshot = serde_json::from_slice(&bytes)?;
snapshot.validate(year)?;
Ok(Some(snapshot))
}
pub fn save(
&self,
account_id: NonZeroU64,
snapshot: &StarSnapshot,
) -> Result<(), StarStoreError> {
snapshot.validate(snapshot.year)?;
let json = serde_json::to_string_pretty(snapshot)?;
cache::store(&self.snapshot_path(account_id, snapshot.year), &json)?;
Ok(())
}
pub(super) fn snapshot_path(&self, account_id: NonZeroU64, year: usize) -> PathBuf {
Path::new(&self.root)
.join(account_id.to_string())
.join(format!("{year}.json"))
}
}
#[cfg(test)]
mod tests {
use std::fs;
use std::num::NonZeroU64;
use tempfile::tempdir;
use super::{StarSnapshot, StarStore, StarStoreError, VerifiedStar};
#[test]
fn distinguishes_earned_missing_and_unknown_stars() {
let snapshot = StarSnapshot::new(2025, 100, vec![2, 0, 1]).unwrap();
assert_eq!(snapshot.star(1, 2), VerifiedStar::Earned);
assert_eq!(snapshot.star(2, 1), VerifiedStar::Missing);
assert_eq!(snapshot.star(3, 1), VerifiedStar::Earned);
assert_eq!(snapshot.star(3, 2), VerifiedStar::Missing);
assert_eq!(snapshot.star(4, 1), VerifiedStar::Unknown);
assert_eq!(snapshot.synced_at_unix_seconds(), 100);
}
#[test]
fn keeps_snapshots_isolated_when_switching_accounts() {
let directory = tempdir().unwrap();
let store = StarStore {
root: directory.path().join("stars"),
};
let first = NonZeroU64::new(123).unwrap();
let second = NonZeroU64::new(456).unwrap();
let first_snapshot = StarSnapshot::new(2025, 100, vec![2]).unwrap();
store.save(first, &first_snapshot).unwrap();
assert_eq!(store.load(second, 2025).unwrap(), None);
assert_eq!(store.load(first, 2024).unwrap(), None);
let second_snapshot = StarSnapshot::new(2025, 200, vec![0]).unwrap();
store.save(second, &second_snapshot).unwrap();
assert_eq!(store.load(second, 2025).unwrap(), Some(second_snapshot));
assert_eq!(store.load(first, 2025).unwrap(), Some(first_snapshot));
}
#[test]
fn validates_edition_lengths_and_star_counts() {
assert!(StarSnapshot::new(2024, 100, vec![0; 25]).is_ok());
assert!(matches!(
StarSnapshot::new(2025, 100, vec![0; 13]),
Err(StarStoreError::InvalidSnapshot),
));
assert!(matches!(
StarSnapshot::new(2025, 100, vec![3]),
Err(StarStoreError::InvalidSnapshot),
));
}
#[test]
fn rejects_unknown_snapshot_versions() {
let directory = tempdir().unwrap();
let store = StarStore {
root: directory.path().join("stars"),
};
let account = NonZeroU64::new(123).unwrap();
let path = store.snapshot_path(account, 2025);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, br#"{"schema_version":2}"#).unwrap();
assert!(matches!(
store.load(account, 2025),
Err(StarStoreError::UnsupportedVersion(2)),
));
}
}