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
//! Bevy adapter: a [`LicensingPlugin`] that owns the async check on the `IoTaskPool` and
//! exposes the gate as resources + a message API.
//!
//! Provides the same `start_license_check` / `poll_license_job` flow, but **UI-decoupled**:
//! instead of querying specific button components, the app sends [`ActivateLicense`] /
//! [`ClearLicense`] messages and reads [`Licensed`] / [`LicenseLog`]. The app keeps full
//! control of its widgets, focus, and "Buy" button (see [`open_url`]).

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

use bevy::prelude::*;
use bevy::tasks::{block_on, IoTaskPool, Task};

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

// Re-exported so existing `rustify_licensing::bevy::open_url` call sites keep working.
pub use crate::open_url;

/// Persisted license state (key / fingerprint / last validated), as a Bevy resource.
#[derive(Resource, Default)]
pub struct License(pub LicenseState);

/// Runtime unlock status. `unlocked()` ⇒ paid features on. Change-detected, so a
/// visibility system can react with `if licensed.is_changed()`.
#[derive(Resource, Clone, Copy, PartialEq, Eq, Default)]
pub struct Licensed(pub LicenseStatus);

impl Licensed {
    pub fn unlocked(&self) -> bool {
        self.0.unlocked()
    }
}

/// Human-readable progress/result lines, newest last. The app renders these however it
/// likes (e.g. fold them into an in-app log).
#[derive(Resource, Default)]
pub struct LicenseLog(pub Vec<String>);

/// The shared per-app config, readable by the app (e.g. for `buy_url`).
#[derive(Resource, Clone)]
pub struct LicenseSettings(pub LicenseConfig);

/// The chosen backend, type-erased.
#[derive(Resource, Clone)]
struct LicenseBackend(Arc<dyn LicenseProvider>);

/// One in-flight validation (none = idle).
#[derive(Resource, Default)]
pub struct LicenseJob(Option<LicenseTask>);

struct LicenseTask {
    task: Task<Result<bool, CheckErr>>,
    rx: Mutex<Receiver<String>>,
}

/// Message: (re)validate the currently entered key. Send this from your "Activate" button.
#[derive(Message)]
pub struct ActivateLicense;

/// Message: clear the stored key (ready to paste a new one). The app handles its own
/// field focus afterward.
#[derive(Message)]
pub struct ClearLicense;

/// Registers the licensing resources, systems, and messages, kicking off a startup check.
pub struct LicensingPlugin {
    config: LicenseConfig,
    provider: Arc<dyn LicenseProvider>,
}

impl LicensingPlugin {
    /// Use any provider.
    pub fn new(config: LicenseConfig, provider: Arc<dyn LicenseProvider>) -> Self {
        Self { config, provider }
    }

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

impl Plugin for LicensingPlugin {
    fn build(&self, app: &mut App) {
        let state = LicenseState::load(&self.config.storage);
        app.insert_resource(License(state))
            .insert_resource(Licensed::default())
            .init_resource::<LicenseLog>()
            .init_resource::<LicenseJob>()
            .insert_resource(LicenseSettings(self.config.clone()))
            .insert_resource(LicenseBackend(self.provider.clone()))
            .add_message::<ActivateLicense>()
            .add_message::<ClearLicense>()
            .add_systems(Startup, start_license_check)
            .add_systems(Update, (handle_activate, handle_clear, poll_license_job));
    }
}

fn log_line(log: &mut LicenseLog, line: impl Into<String>) {
    log.0.push(line.into());
}

/// Spawn the blocking check on the `IoTaskPool`, streaming progress over a channel.
fn spawn_check(state: &LicenseState, provider: &Arc<dyn LicenseProvider>, job: &mut LicenseJob) {
    let (tx, rx) = channel();
    let probe = LicenseState {
        key: state.key.trim().to_string(),
        fingerprint: state.fingerprint.clone(),
        last_validated: state.last_validated,
    };
    let provider = provider.clone();
    let task = IoTaskPool::get().spawn(async move {
        let mut progress = |m: String| {
            let _ = tx.send(m);
        };
        run_check(provider.as_ref(), &probe, &mut progress)
    });
    job.0 = Some(LicenseTask {
        task,
        rx: Mutex::new(rx),
    });
}

/// Startup: kick off a validation if we have a stored key; otherwise lock.
fn start_license_check(
    license: Res<License>,
    backend: Res<LicenseBackend>,
    mut job: ResMut<LicenseJob>,
    mut status: ResMut<Licensed>,
) {
    if license.0.key.trim().is_empty() {
        status.0 = LicenseStatus::Locked;
    } else {
        spawn_check(&license.0, &backend.0, &mut job); // stays Unknown until it resolves
    }
}

/// [`ActivateLicense`] → (re)validate the currently entered key (if idle).
fn handle_activate(
    mut messages: MessageReader<ActivateLicense>,
    license: Res<License>,
    backend: Res<LicenseBackend>,
    mut job: ResMut<LicenseJob>,
    mut status: ResMut<Licensed>,
    mut log: ResMut<LicenseLog>,
) {
    if messages.read().count() == 0 {
        return;
    }
    if license.0.key.trim().is_empty() {
        log_line(&mut log, "paste a license key first");
    } else if job.0.is_none() {
        status.0 = LicenseStatus::Unknown;
        spawn_check(&license.0, &backend.0, &mut job);
    }
}

/// [`ClearLicense`] → empty the stored key.
fn handle_clear(mut messages: MessageReader<ClearLicense>, mut license: ResMut<License>) {
    if messages.read().count() > 0 {
        license.0.key.clear();
    }
}

/// Drain progress; when the check finishes, fold it into [`Licensed`] (honoring grace)
/// and persist on success.
fn poll_license_job(
    mut job: ResMut<LicenseJob>,
    mut license: ResMut<License>,
    settings: Res<LicenseSettings>,
    mut status: ResMut<Licensed>,
    mut log: ResMut<LicenseLog>,
) {
    let mut finished = false;
    if let Some(j) = job.0.as_mut() {
        while let Ok(line) = j.rx.lock().unwrap().try_recv() {
            log_line(&mut log, line);
        }
        finished = j.task.is_finished();
    }
    if !finished {
        return;
    }
    let j = job.0.take().unwrap();
    let result = block_on(j.task);
    let res = resolve(result, &mut license.0, now_secs(), settings.0.grace_secs);
    status.0 = res.status;
    if status.0 == LicenseStatus::Active {
        license.0.save(&settings.0.storage);
    }
    if let Some(msg) = res.message {
        log_line(&mut log, msg);
    }
}