Skip to main content

rustify_licensing/adapters/
worker.rs

1//! A framework-agnostic, threaded license worker for immediate-mode GUIs (egui, Slint,
2//! …) and CLIs — anything with an update/poll loop and no async runtime. It runs the
3//! blocking check off the UI thread on a `std::thread` and surfaces status + progress
4//! through [`poll`](LicenseWorker::poll), which you call once per frame.
5//!
6//! This is the non-Bevy counterpart to [`crate::adapters::bevy`]: same core engine, no
7//! framework dependency at all (just `std`).
8
9use std::sync::mpsc::{channel, Receiver};
10use std::sync::Arc;
11
12use crate::core::config::LicenseConfig;
13use crate::core::engine::{resolve, run_check};
14use crate::core::state::{now_secs, LicenseState};
15use crate::core::status::LicenseStatus;
16use crate::provider::{KeygenProvider, LicenseProvider};
17
18struct Done {
19    status: LicenseStatus,
20    last_validated: Option<u64>,
21    message: Option<String>,
22}
23
24struct Job {
25    progress: Receiver<String>,
26    done: Receiver<Done>,
27}
28
29/// Owns the persisted license state plus an optional background check. Drive it from your
30/// UI loop: call [`poll`](Self::poll) every frame, read [`status`](Self::status) /
31/// [`unlocked`](Self::unlocked) / [`log`](Self::log), and trigger work with
32/// [`activate`](Self::activate).
33pub struct LicenseWorker {
34    config: LicenseConfig,
35    provider: Arc<dyn LicenseProvider>,
36    state: LicenseState,
37    status: LicenseStatus,
38    log: Vec<String>,
39    job: Option<Job>,
40}
41
42impl LicenseWorker {
43    /// Load persisted state and, if a key is stored, kick off a validation immediately.
44    pub fn new(config: LicenseConfig, provider: Arc<dyn LicenseProvider>) -> Self {
45        let state = LicenseState::load(&config.storage);
46        let mut w = Self {
47            config,
48            provider,
49            state,
50            status: LicenseStatus::Unknown,
51            log: Vec::new(),
52            job: None,
53        };
54        if w.state.key.trim().is_empty() {
55            w.status = LicenseStatus::Locked;
56        } else {
57            w.start_check();
58        }
59        w
60    }
61
62    /// Convenience: wire a [`KeygenProvider`] from the config.
63    pub fn keygen(config: LicenseConfig) -> Self {
64        let provider = Arc::new(KeygenProvider::from_config(&config));
65        Self::new(config, provider)
66    }
67
68    pub fn status(&self) -> LicenseStatus {
69        self.status
70    }
71    pub fn unlocked(&self) -> bool {
72        self.status.unlocked()
73    }
74    pub fn log(&self) -> &[String] {
75        &self.log
76    }
77    /// The most recent log line, if any.
78    pub fn last_message(&self) -> Option<&str> {
79        self.log.last().map(String::as_str)
80    }
81    /// Is a validation currently in flight?
82    pub fn is_checking(&self) -> bool {
83        self.job.is_some()
84    }
85
86    /// The current key (e.g. to render the field).
87    pub fn key(&self) -> &str {
88        &self.state.key
89    }
90    /// Replace the key (e.g. from a text field or a paste).
91    pub fn set_key(&mut self, key: impl Into<String>) {
92        self.state.key = key.into();
93    }
94    /// Mutable access to the key, for binding directly to a GUI text field.
95    pub fn key_mut(&mut self) -> &mut String {
96        &mut self.state.key
97    }
98    /// Clear the key.
99    pub fn clear_key(&mut self) {
100        self.state.key.clear();
101    }
102    /// Where a "Buy" button should open.
103    pub fn buy_url(&self) -> &str {
104        &self.config.buy_url
105    }
106
107    /// (Re)validate the current key, unless a check is already running.
108    pub fn activate(&mut self) {
109        if self.state.key.trim().is_empty() {
110            self.log.push("paste a license key first".into());
111            return;
112        }
113        if self.job.is_none() {
114            self.status = LicenseStatus::Unknown;
115            self.start_check();
116        }
117    }
118
119    fn start_check(&mut self) {
120        let (tx_progress, progress) = channel::<String>();
121        let (tx_done, done) = channel::<Done>();
122        let probe = LicenseState {
123            key: self.state.key.trim().to_string(),
124            fingerprint: self.state.fingerprint.clone(),
125            last_validated: self.state.last_validated,
126        };
127        let provider = self.provider.clone();
128        let grace = self.config.grace_secs;
129        std::thread::spawn(move || {
130            let mut report = |m: String| {
131                let _ = tx_progress.send(m);
132            };
133            let result = run_check(provider.as_ref(), &probe, &mut report);
134            let mut st = probe;
135            let res = resolve(result, &mut st, now_secs(), grace);
136            let _ = tx_done.send(Done {
137                status: res.status,
138                last_validated: st.last_validated,
139                message: res.message,
140            });
141        });
142        self.job = Some(Job { progress, done });
143    }
144
145    /// Drain progress and apply a finished check. Call once per UI frame. Returns `true`
146    /// if the status changed on this call (handy to request a repaint).
147    pub fn poll(&mut self) -> bool {
148        // Collect first so the borrow of `self.job` ends before we mutate `self`.
149        let (new_lines, finished) = match self.job.as_ref() {
150            None => return false,
151            Some(job) => {
152                let mut lines = Vec::new();
153                while let Ok(m) = job.progress.try_recv() {
154                    lines.push(m);
155                }
156                (lines, job.done.try_recv().ok())
157            }
158        };
159        self.log.extend(new_lines);
160
161        let mut changed = false;
162        if let Some(done) = finished {
163            changed = self.status != done.status;
164            self.status = done.status;
165            self.state.last_validated = done.last_validated;
166            if self.status == LicenseStatus::Active {
167                self.state.save(&self.config.storage);
168            }
169            if let Some(m) = done.message {
170                self.log.push(m);
171            }
172            self.job = None;
173        }
174        changed
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use crate::core::config::StorageConfig;
182    use crate::core::error::CheckErr;
183    use std::time::Duration;
184
185    struct Mock(Result<bool, CheckErr>);
186    impl LicenseProvider for Mock {
187        fn check(&self, _: &str, _: &str, p: &mut dyn FnMut(String)) -> Result<bool, CheckErr> {
188            p("checking".into());
189            self.0.clone()
190        }
191    }
192
193    fn config(tag: &str) -> LicenseConfig {
194        let mut path = std::env::temp_dir();
195        path.push(format!("rustify-worker-{tag}-{}.env", std::process::id()));
196        let _ = std::fs::remove_file(&path);
197        LicenseConfig {
198            account_id: "a".into(),
199            api_base: "x".into(),
200            grace_secs: 100,
201            storage: StorageConfig { path, dev_shadow: None, env_key_var: None },
202            buy_url: "u".into(),
203        }
204    }
205
206    /// Poll until the in-flight check settles (or time out).
207    fn settle(w: &mut LicenseWorker) {
208        for _ in 0..500 {
209            w.poll();
210            if !w.is_checking() {
211                return;
212            }
213            std::thread::sleep(Duration::from_millis(2));
214        }
215        panic!("worker check did not settle");
216    }
217
218    #[test]
219    fn empty_key_starts_locked_without_a_job() {
220        let mut w = LicenseWorker::new(config("empty"), Arc::new(Mock(Ok(true))));
221        assert_eq!(w.status(), LicenseStatus::Locked);
222        assert!(!w.is_checking());
223    }
224
225    #[test]
226    fn valid_key_activates_and_persists() {
227        let cfg = config("ok");
228        let mut w = LicenseWorker::new(cfg.clone(), Arc::new(Mock(Ok(true))));
229        w.set_key("K");
230        w.activate();
231        assert!(w.is_checking());
232        settle(&mut w);
233        assert_eq!(w.status(), LicenseStatus::Active);
234        assert!(LicenseState::load(&cfg.storage).last_validated.is_some());
235        let _ = std::fs::remove_file(cfg.storage.resolve());
236    }
237
238    #[test]
239    fn denied_key_locks() {
240        let mut w = LicenseWorker::new(config("denied"), Arc::new(Mock(Err(CheckErr::Denied("403".into())))));
241        w.set_key("K");
242        w.activate();
243        settle(&mut w);
244        assert_eq!(w.status(), LicenseStatus::Locked);
245    }
246}