fusion-stack-laravel-rust 0.2.1

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! Version usage, as the PHP package's `VersionUsage` records it: one row in `api_version_usage`
//! per client, version and day (UTC) the client used the version, so you can see who still uses a
//! version before you retire it. The cache remembers each day's rows, so a client writes at most
//! once a day per version.

use laravel::db::{self, values};
use sha2::{Digest, Sha256};

use crate::auth::ApiClient;
use crate::time;
use crate::versioning::ApiVersion;

/// The table rows go to.
pub const TABLE: &str = "api_version_usage";

/// Records that `client` used `version` today. Failures are left out of the response: usage is
/// a record for you, not part of the request.
pub(crate) async fn record(client: &ApiClient, version: &ApiVersion) {
    let now = time::now();
    let day = time::date(now);
    let version = version.to_string();
    let hash: String = Sha256::digest(format!("{}\n{version}", client.id).as_bytes())
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    let key = format!("fusion-stack:version-usage:{day}:{hash}");
    let until_tomorrow = 86_400 - now.rem_euclid(86_400) + 1;
    let Ok(store) = laravel::cache::manager().default_store() else {
        return;
    };
    let first = store
        .add(
            &key,
            true,
            std::time::Duration::from_secs(u64::try_from(until_tomorrow).unwrap_or(86_400)),
        )
        .await
        .unwrap_or(false);
    if first {
        let _ = db::table(TABLE)
            .insert_or_ignore(values! {
                client_id: client.id.clone(),
                version: version,
                date: day,
                created_at: laravel::now().timestamp(),
            })
            .await;
    }
}