Skip to main content

rustify_licensing/adapters/
headless.rs

1//! A blocking, no-UI driver: run a check on the calling thread and fold it into a
2//! status, persisting on success. For CLIs, integration tests, and the example.
3
4use crate::core::config::LicenseConfig;
5use crate::core::engine::{resolve, run_check};
6use crate::core::state::{now_secs, LicenseState};
7use crate::core::status::LicenseStatus;
8use crate::provider::LicenseProvider;
9
10/// Validate `state`'s key against `provider`, fold the result into a [`LicenseStatus`]
11/// (honoring offline grace, failing closed on denial), and persist `last_validated` on
12/// success. An empty key short-circuits to [`LicenseStatus::Locked`] with no network call.
13pub fn check_blocking(
14    config: &LicenseConfig,
15    provider: &dyn LicenseProvider,
16    state: &mut LicenseState,
17    mut progress: impl FnMut(String),
18) -> LicenseStatus {
19    if state.key.trim().is_empty() {
20        return LicenseStatus::Locked;
21    }
22    let result = run_check(provider, state, &mut progress);
23    let res = resolve(result, state, now_secs(), config.grace_secs);
24    if let Some(msg) = res.message {
25        progress(msg);
26    }
27    if res.status == LicenseStatus::Active {
28        state.save(&config.storage);
29    }
30    res.status
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36    use crate::core::config::StorageConfig;
37    use crate::core::error::CheckErr;
38
39    struct Mock(Result<bool, CheckErr>);
40    impl LicenseProvider for Mock {
41        fn check(
42            &self,
43            _key: &str,
44            _fp: &str,
45            progress: &mut dyn FnMut(String),
46        ) -> Result<bool, CheckErr> {
47            progress("mock check".into());
48            self.0.clone()
49        }
50    }
51
52    fn config(tag: &str) -> LicenseConfig {
53        let mut p = std::env::temp_dir();
54        p.push(format!("rustify-headless-{tag}-{}.env", std::process::id()));
55        let _ = std::fs::remove_file(&p);
56        LicenseConfig {
57            account_id: "acct".into(),
58            api_base: "https://example/v1".into(),
59            grace_secs: 100,
60            storage: StorageConfig {
61                path: p,
62                dev_shadow: None,
63                env_key_var: None,
64            },
65            buy_url: "https://example/#pricing".into(),
66        }
67    }
68
69    fn keyed() -> LicenseState {
70        LicenseState {
71            key: "K".into(),
72            fingerprint: "fp".into(),
73            last_validated: None,
74        }
75    }
76
77    #[test]
78    fn empty_key_locks_without_calling_provider() {
79        let cfg = config("empty");
80        // A mock that would panic if called proves we short-circuit.
81        struct Boom;
82        impl LicenseProvider for Boom {
83            fn check(&self, _: &str, _: &str, _: &mut dyn FnMut(String)) -> Result<bool, CheckErr> {
84                panic!("provider must not be called for an empty key");
85            }
86        }
87        let mut st = LicenseState::default();
88        assert_eq!(
89            check_blocking(&cfg, &Boom, &mut st, |_| {}),
90            LicenseStatus::Locked
91        );
92    }
93
94    #[test]
95    fn valid_key_activates_and_persists() {
96        let cfg = config("ok");
97        let mut st = keyed();
98        let status = check_blocking(&cfg, &Mock(Ok(true)), &mut st, |_| {});
99        assert_eq!(status, LicenseStatus::Active);
100        assert!(st.last_validated.is_some());
101        // Persisted to disk.
102        let reloaded = LicenseState::load(&cfg.storage);
103        assert!(reloaded.last_validated.is_some());
104        let _ = std::fs::remove_file(cfg.storage.resolve());
105    }
106
107    #[test]
108    fn denied_locks() {
109        let cfg = config("denied");
110        let mut st = keyed();
111        let status = check_blocking(&cfg, &Mock(Err(CheckErr::Denied("403".into()))), &mut st, |_| {});
112        assert_eq!(status, LicenseStatus::Locked);
113        let _ = std::fs::remove_file(cfg.storage.resolve());
114    }
115}