use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::{LicenceClass, ModelManifest};
use crate::digest::Digest;
use crate::error::{Result, VisionError};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LicenceAcceptance {
pub model: String,
pub licence_id: String,
pub licence_url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub licence_text_digest: Option<Digest>,
pub principal: String,
pub accepted_at: DateTime<Utc>,
}
impl LicenceAcceptance {
pub fn of(manifest: &ModelManifest, principal: impl Into<String>) -> Self {
Self {
model: manifest.id.clone(),
licence_id: manifest.licence.id.clone(),
licence_url: manifest.licence.url.clone(),
licence_text_digest: None,
principal: principal.into(),
accepted_at: Utc::now(),
}
}
fn covers(&self, manifest: &ModelManifest) -> bool {
self.model == manifest.id
&& self.licence_id == manifest.licence.id
&& self.licence_url == manifest.licence.url
}
}
pub trait AcceptanceStore: Send + Sync {
fn acceptances(&self) -> Result<Vec<LicenceAcceptance>>;
fn record(&self, acceptance: LicenceAcceptance) -> Result<()>;
}
#[derive(Debug, Default)]
pub struct InMemoryAcceptanceStore {
acceptances: Mutex<Vec<LicenceAcceptance>>,
}
impl InMemoryAcceptanceStore {
pub fn new() -> Self {
Self::default()
}
}
impl AcceptanceStore for InMemoryAcceptanceStore {
fn acceptances(&self) -> Result<Vec<LicenceAcceptance>> {
Ok(self.acceptances.lock().unwrap_or_else(|e| e.into_inner()).clone())
}
fn record(&self, acceptance: LicenceAcceptance) -> Result<()> {
self.acceptances.lock().unwrap_or_else(|e| e.into_inner()).push(acceptance);
Ok(())
}
}
#[derive(Debug)]
pub struct FileAcceptanceStore {
path: PathBuf,
lock: Mutex<()>,
}
impl FileAcceptanceStore {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into(), lock: Mutex::new(()) }
}
pub fn in_project(project: &Path) -> Self {
Self::new(project.join(".adk").join("vision").join("licences.json"))
}
fn read(&self) -> Result<Vec<LicenceAcceptance>> {
match std::fs::read_to_string(&self.path) {
Ok(text) => serde_json::from_str(&text).map_err(|e| {
VisionError::InvalidInput(format!("{} is not valid: {e}", self.path.display()))
}),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
Err(err) => Err(VisionError::io("could not read", &self.path, err)),
}
}
}
impl AcceptanceStore for FileAcceptanceStore {
fn acceptances(&self) -> Result<Vec<LicenceAcceptance>> {
let _guard = self.lock.lock().unwrap_or_else(|e| e.into_inner());
self.read()
}
fn record(&self, acceptance: LicenceAcceptance) -> Result<()> {
let _guard = self.lock.lock().unwrap_or_else(|e| e.into_inner());
let mut all = self.read()?;
all.push(acceptance);
if let Some(parent) = self.path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| VisionError::io("could not create", parent, e))?;
}
let text = serde_json::to_string_pretty(&all)
.map_err(|e| VisionError::InvalidInput(e.to_string()))?;
let tmp = self.path.with_extension("json.tmp");
std::fs::write(&tmp, text).map_err(|e| VisionError::io("could not write", &tmp, e))?;
std::fs::rename(&tmp, &self.path)
.map_err(|e| VisionError::io("could not replace", &self.path, e))
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LicencePolicy {
#[serde(default)]
pub allow: BTreeSet<String>,
}
impl LicencePolicy {
pub fn new() -> Self {
Self::default()
}
pub fn allowing(mut self, model: impl Into<String>) -> Self {
self.allow.insert(model.into());
self
}
}
pub struct LicenceGate<'a> {
policy: &'a LicencePolicy,
acceptances: &'a dyn AcceptanceStore,
}
impl<'a> LicenceGate<'a> {
pub fn new(policy: &'a LicencePolicy, acceptances: &'a dyn AcceptanceStore) -> Self {
Self { policy, acceptances }
}
pub fn check(&self, manifest: &ModelManifest) -> Result<()> {
match manifest.licence.class {
LicenceClass::Permissive => Ok(()),
LicenceClass::UseRestricted => {
if self.acceptances.acceptances()?.iter().any(|a| a.covers(manifest)) {
Ok(())
} else {
Err(VisionError::LicenceAcceptanceRequired {
model: manifest.id.clone(),
licence_url: manifest.licence.url.clone(),
})
}
}
class @ (LicenceClass::NonCommercial | LicenceClass::Copyleft) => {
if self.policy.allow.contains(&manifest.id) {
Ok(())
} else {
Err(VisionError::LicenceNotAllowed {
model: manifest.id.clone(),
class: class.to_string(),
licence_url: manifest.licence.url.clone(),
})
}
}
}
}
}