use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use super::codec::{hex_encode, write_atomic};
use super::hardware::HardwareProfile;
use super::LicenceError;
#[derive(Debug, Clone)]
pub struct TrialPolicy {
pub duration: Duration,
pub features: Vec<String>,
pub quotas: BTreeMap<String, u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TrialRecord {
pub v: u32,
pub started_at: DateTime<Utc>,
pub installation_id: String,
pub hardware_digest: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrialStatus {
pub started_at: DateTime<Utc>,
pub expires_at: DateTime<Utc>,
pub active: bool,
pub remaining_days: i64,
pub ended: Option<TrialEnd>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum TrialEnd {
Expired,
ClockRolledBack,
}
impl TrialRecord {
pub fn start(now: DateTime<Utc>, installation_id: &str, hardware: &HardwareProfile) -> Self {
Self {
v: 1,
started_at: now,
installation_id: installation_id.to_string(),
hardware_digest: hardware.digest(),
}
}
pub fn earliest(a: Option<Self>, b: Option<Self>) -> Option<Self> {
match (a, b) {
(Some(a), Some(b)) => Some(if b.started_at < a.started_at { b } else { a }),
(a, b) => a.or(b),
}
}
pub fn status(&self, policy: &TrialPolicy, now: DateTime<Utc>, clock: &ClockStatus) -> TrialStatus {
let expires_at = self.started_at + policy.duration;
let ended = if matches!(clock, ClockStatus::RolledBack { .. }) || now < self.started_at {
Some(TrialEnd::ClockRolledBack)
} else if now >= expires_at {
Some(TrialEnd::Expired)
} else {
None
};
let remaining_days = match ended {
Some(_) => 0,
None => {
let left = expires_at - now;
let days = left.num_days();
if left > Duration::days(days) { days + 1 } else { days }
}
};
TrialStatus {
started_at: self.started_at,
expires_at,
active: ended.is_none(),
remaining_days,
ended,
}
}
pub fn load(path: &Path) -> Result<Option<Self>, LicenceError> {
match std::fs::read(path) {
Ok(bytes) => serde_json::from_slice(&bytes)
.map(Some)
.map_err(|e| LicenceError::State(format!("{}: {e}", path.display()))),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(LicenceError::State(format!("{}: {e}", path.display()))),
}
}
pub fn save(&self, path: &Path) -> Result<(), LicenceError> {
let json = serde_json::to_vec_pretty(self).map_err(|e| LicenceError::State(e.to_string()))?;
write_atomic(path, &json).map_err(|e| LicenceError::State(format!("{}: {e}", path.display())))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "clock", rename_all = "camelCase")]
pub enum ClockStatus {
Ok,
RolledBack { mark: DateTime<Utc> },
}
#[derive(Debug, Clone)]
pub struct ClockMark {
path: PathBuf,
highest: Option<DateTime<Utc>>,
guard: Duration,
}
impl ClockMark {
pub fn open(path: &Path, guard: Duration) -> Result<Self, LicenceError> {
let highest = match std::fs::read_to_string(path) {
Ok(text) => Some(
DateTime::parse_from_rfc3339(text.trim())
.map_err(|e| LicenceError::State(format!("{}: {e}", path.display())))?
.with_timezone(&Utc),
),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(LicenceError::State(format!("{}: {e}", path.display()))),
};
Ok(Self { path: path.to_path_buf(), highest, guard })
}
pub fn check(&self, now: DateTime<Utc>) -> ClockStatus {
match self.highest {
Some(mark) if now + self.guard < mark => ClockStatus::RolledBack { mark },
_ => ClockStatus::Ok,
}
}
pub fn observe(&mut self, now: DateTime<Utc>) -> Result<ClockStatus, LicenceError> {
let status = self.check(now);
if self.highest.is_none_or(|h| now > h) {
write_atomic(&self.path, now.to_rfc3339().as_bytes())
.map_err(|e| LicenceError::State(format!("{}: {e}", self.path.display())))?;
self.highest = Some(now);
}
Ok(status)
}
pub fn reset(&mut self, now: DateTime<Utc>) -> Result<(), LicenceError> {
write_atomic(&self.path, now.to_rfc3339().as_bytes())
.map_err(|e| LicenceError::State(format!("{}: {e}", self.path.display())))?;
self.highest = Some(now);
Ok(())
}
pub fn highest(&self) -> Option<DateTime<Utc>> {
self.highest
}
}
pub fn random_uuid() -> Result<String, LicenceError> {
let mut raw = [0u8; 16];
ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut raw)
.map_err(|_| LicenceError::State("random source failed".to_string()))?;
raw[6] = (raw[6] & 0x0f) | 0x40;
raw[8] = (raw[8] & 0x3f) | 0x80;
let h = hex_encode(&raw);
Ok(format!("{}-{}-{}-{}-{}", &h[..8], &h[8..12], &h[12..16], &h[16..20], &h[20..]))
}
pub fn installation_id(path: &Path) -> Result<(String, bool), LicenceError> {
match std::fs::read_to_string(path) {
Ok(text) if !text.trim().is_empty() => return Ok((text.trim().to_string(), false)),
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(LicenceError::State(format!("{}: {e}", path.display()))),
}
let id = random_uuid()?;
write_atomic(path, id.as_bytes())
.map_err(|e| LicenceError::State(format!("{}: {e}", path.display())))?;
Ok((id, true))
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
fn t(day: u32, hour: u32) -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 11, day, hour, 0, 0).unwrap()
}
fn policy() -> TrialPolicy {
TrialPolicy { duration: Duration::days(14), features: vec![], quotas: BTreeMap::new() }
}
#[test]
fn trial_runs_fourteen_days() {
let record = TrialRecord::start(t(1, 12), "id", &HardwareProfile::default());
let s = record.status(&policy(), t(1, 13), &ClockStatus::Ok);
assert!(s.active);
assert_eq!(s.remaining_days, 14);
assert_eq!(record.status(&policy(), t(14, 13), &ClockStatus::Ok).remaining_days, 1);
let end = record.status(&policy(), t(15, 12), &ClockStatus::Ok);
assert!(!end.active);
assert_eq!(end.ended, Some(TrialEnd::Expired));
}
#[test]
fn clock_before_start_ends_trial() {
let record = TrialRecord::start(t(10, 0), "id", &HardwareProfile::default());
let s = record.status(&policy(), t(9, 0), &ClockStatus::Ok);
assert_eq!(s.ended, Some(TrialEnd::ClockRolledBack));
let s = record.status(&policy(), t(11, 0), &ClockStatus::RolledBack { mark: t(20, 0) });
assert!(!s.active);
}
#[test]
fn earliest_trace_wins() {
let a = TrialRecord::start(t(5, 0), "a", &HardwareProfile::default());
let b = TrialRecord::start(t(3, 0), "b", &HardwareProfile::default());
assert_eq!(TrialRecord::earliest(Some(a.clone()), Some(b.clone())), Some(b.clone()));
assert_eq!(TrialRecord::earliest(None, Some(a.clone())), Some(a));
assert_eq!(TrialRecord::earliest(None, None), None);
}
#[test]
fn trial_file_roundtrip() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("trial.mark");
assert_eq!(TrialRecord::load(&path).unwrap(), None);
let record = TrialRecord::start(t(1, 0), "id", &HardwareProfile::default());
record.save(&path).unwrap();
assert_eq!(TrialRecord::load(&path).unwrap(), Some(record));
std::fs::write(&path, "garbage").unwrap();
assert!(TrialRecord::load(&path).is_err());
}
#[test]
fn clock_mark_detects_roll_back_beyond_guard() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("clock.mark");
let mut mark = ClockMark::open(&path, Duration::hours(24)).unwrap();
assert_eq!(mark.observe(t(10, 0)).unwrap(), ClockStatus::Ok);
assert_eq!(mark.observe(t(9, 12)).unwrap(), ClockStatus::Ok);
assert_eq!(mark.highest(), Some(t(10, 0)));
let reopened = ClockMark::open(&path, Duration::hours(24)).unwrap();
assert_eq!(reopened.check(t(8, 0)), ClockStatus::RolledBack { mark: t(10, 0) });
assert_eq!(reopened.check(t(11, 0)), ClockStatus::Ok);
let mut reset = reopened;
reset.reset(t(8, 0)).unwrap();
assert_eq!(reset.check(t(8, 0)), ClockStatus::Ok);
}
#[test]
fn installation_id_is_created_once() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("secrets/installation.id");
let (id, created) = installation_id(&path).unwrap();
assert!(created);
assert_eq!(id.len(), 36);
assert_eq!(installation_id(&path).unwrap(), (id, false));
}
}