rustify-licensing 0.1.0

Framework-agnostic in-app licensing (validate / machine-activate / offline-grace) for native Rust apps. Keygen provider + Bevy / egui / headless adapters.
Documentation
//! A framework-agnostic, threaded license worker for immediate-mode GUIs (egui, Slint,
//! …) and CLIs — anything with an update/poll loop and no async runtime. It runs the
//! blocking check off the UI thread on a `std::thread` and surfaces status + progress
//! through [`poll`](LicenseWorker::poll), which you call once per frame.
//!
//! This is the non-Bevy counterpart to [`crate::adapters::bevy`]: same core engine, no
//! framework dependency at all (just `std`).

use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;

use crate::core::config::LicenseConfig;
use crate::core::engine::{resolve, run_check};
use crate::core::state::{now_secs, LicenseState};
use crate::core::status::LicenseStatus;
use crate::provider::{KeygenProvider, LicenseProvider};

struct Done {
    status: LicenseStatus,
    last_validated: Option<u64>,
    message: Option<String>,
}

struct Job {
    progress: Receiver<String>,
    done: Receiver<Done>,
}

/// Owns the persisted license state plus an optional background check. Drive it from your
/// UI loop: call [`poll`](Self::poll) every frame, read [`status`](Self::status) /
/// [`unlocked`](Self::unlocked) / [`log`](Self::log), and trigger work with
/// [`activate`](Self::activate).
pub struct LicenseWorker {
    config: LicenseConfig,
    provider: Arc<dyn LicenseProvider>,
    state: LicenseState,
    status: LicenseStatus,
    log: Vec<String>,
    job: Option<Job>,
}

impl LicenseWorker {
    /// Load persisted state and, if a key is stored, kick off a validation immediately.
    pub fn new(config: LicenseConfig, provider: Arc<dyn LicenseProvider>) -> Self {
        let state = LicenseState::load(&config.storage);
        let mut w = Self {
            config,
            provider,
            state,
            status: LicenseStatus::Unknown,
            log: Vec::new(),
            job: None,
        };
        if w.state.key.trim().is_empty() {
            w.status = LicenseStatus::Locked;
        } else {
            w.start_check();
        }
        w
    }

    /// Convenience: wire a [`KeygenProvider`] from the config.
    pub fn keygen(config: LicenseConfig) -> Self {
        let provider = Arc::new(KeygenProvider::from_config(&config));
        Self::new(config, provider)
    }

    pub fn status(&self) -> LicenseStatus {
        self.status
    }
    pub fn unlocked(&self) -> bool {
        self.status.unlocked()
    }
    pub fn log(&self) -> &[String] {
        &self.log
    }
    /// The most recent log line, if any.
    pub fn last_message(&self) -> Option<&str> {
        self.log.last().map(String::as_str)
    }
    /// Is a validation currently in flight?
    pub fn is_checking(&self) -> bool {
        self.job.is_some()
    }

    /// The current key (e.g. to render the field).
    pub fn key(&self) -> &str {
        &self.state.key
    }
    /// Replace the key (e.g. from a text field or a paste).
    pub fn set_key(&mut self, key: impl Into<String>) {
        self.state.key = key.into();
    }
    /// Mutable access to the key, for binding directly to a GUI text field.
    pub fn key_mut(&mut self) -> &mut String {
        &mut self.state.key
    }
    /// Clear the key.
    pub fn clear_key(&mut self) {
        self.state.key.clear();
    }
    /// Where a "Buy" button should open.
    pub fn buy_url(&self) -> &str {
        &self.config.buy_url
    }

    /// (Re)validate the current key, unless a check is already running.
    pub fn activate(&mut self) {
        if self.state.key.trim().is_empty() {
            self.log.push("paste a license key first".into());
            return;
        }
        if self.job.is_none() {
            self.status = LicenseStatus::Unknown;
            self.start_check();
        }
    }

    fn start_check(&mut self) {
        let (tx_progress, progress) = channel::<String>();
        let (tx_done, done) = channel::<Done>();
        let probe = LicenseState {
            key: self.state.key.trim().to_string(),
            fingerprint: self.state.fingerprint.clone(),
            last_validated: self.state.last_validated,
        };
        let provider = self.provider.clone();
        let grace = self.config.grace_secs;
        std::thread::spawn(move || {
            let mut report = |m: String| {
                let _ = tx_progress.send(m);
            };
            let result = run_check(provider.as_ref(), &probe, &mut report);
            let mut st = probe;
            let res = resolve(result, &mut st, now_secs(), grace);
            let _ = tx_done.send(Done {
                status: res.status,
                last_validated: st.last_validated,
                message: res.message,
            });
        });
        self.job = Some(Job { progress, done });
    }

    /// Drain progress and apply a finished check. Call once per UI frame. Returns `true`
    /// if the status changed on this call (handy to request a repaint).
    pub fn poll(&mut self) -> bool {
        // Collect first so the borrow of `self.job` ends before we mutate `self`.
        let (new_lines, finished) = match self.job.as_ref() {
            None => return false,
            Some(job) => {
                let mut lines = Vec::new();
                while let Ok(m) = job.progress.try_recv() {
                    lines.push(m);
                }
                (lines, job.done.try_recv().ok())
            }
        };
        self.log.extend(new_lines);

        let mut changed = false;
        if let Some(done) = finished {
            changed = self.status != done.status;
            self.status = done.status;
            self.state.last_validated = done.last_validated;
            if self.status == LicenseStatus::Active {
                self.state.save(&self.config.storage);
            }
            if let Some(m) = done.message {
                self.log.push(m);
            }
            self.job = None;
        }
        changed
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::config::StorageConfig;
    use crate::core::error::CheckErr;
    use std::time::Duration;

    struct Mock(Result<bool, CheckErr>);
    impl LicenseProvider for Mock {
        fn check(&self, _: &str, _: &str, p: &mut dyn FnMut(String)) -> Result<bool, CheckErr> {
            p("checking".into());
            self.0.clone()
        }
    }

    fn config(tag: &str) -> LicenseConfig {
        let mut path = std::env::temp_dir();
        path.push(format!("rustify-worker-{tag}-{}.env", std::process::id()));
        let _ = std::fs::remove_file(&path);
        LicenseConfig {
            account_id: "a".into(),
            api_base: "x".into(),
            grace_secs: 100,
            storage: StorageConfig { path, dev_shadow: None, env_key_var: None },
            buy_url: "u".into(),
        }
    }

    /// Poll until the in-flight check settles (or time out).
    fn settle(w: &mut LicenseWorker) {
        for _ in 0..500 {
            w.poll();
            if !w.is_checking() {
                return;
            }
            std::thread::sleep(Duration::from_millis(2));
        }
        panic!("worker check did not settle");
    }

    #[test]
    fn empty_key_starts_locked_without_a_job() {
        let mut w = LicenseWorker::new(config("empty"), Arc::new(Mock(Ok(true))));
        assert_eq!(w.status(), LicenseStatus::Locked);
        assert!(!w.is_checking());
    }

    #[test]
    fn valid_key_activates_and_persists() {
        let cfg = config("ok");
        let mut w = LicenseWorker::new(cfg.clone(), Arc::new(Mock(Ok(true))));
        w.set_key("K");
        w.activate();
        assert!(w.is_checking());
        settle(&mut w);
        assert_eq!(w.status(), LicenseStatus::Active);
        assert!(LicenseState::load(&cfg.storage).last_validated.is_some());
        let _ = std::fs::remove_file(cfg.storage.resolve());
    }

    #[test]
    fn denied_key_locks() {
        let mut w = LicenseWorker::new(config("denied"), Arc::new(Mock(Err(CheckErr::Denied("403".into())))));
        w.set_key("K");
        w.activate();
        settle(&mut w);
        assert_eq!(w.status(), LicenseStatus::Locked);
    }
}