adk_vision/manifest/
licence.rs1use std::collections::BTreeSet;
4use std::path::{Path, PathBuf};
5use std::sync::Mutex;
6
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10use super::{LicenceClass, ModelManifest};
11use crate::digest::Digest;
12use crate::error::{Result, VisionError};
13
14#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "camelCase")]
20pub struct LicenceAcceptance {
21 pub model: String,
23 pub licence_id: String,
25 pub licence_url: String,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub licence_text_digest: Option<Digest>,
30 pub principal: String,
32 pub accepted_at: DateTime<Utc>,
34}
35
36impl LicenceAcceptance {
37 pub fn of(manifest: &ModelManifest, principal: impl Into<String>) -> Self {
39 Self {
40 model: manifest.id.clone(),
41 licence_id: manifest.licence.id.clone(),
42 licence_url: manifest.licence.url.clone(),
43 licence_text_digest: None,
44 principal: principal.into(),
45 accepted_at: Utc::now(),
46 }
47 }
48
49 fn covers(&self, manifest: &ModelManifest) -> bool {
50 self.model == manifest.id
51 && self.licence_id == manifest.licence.id
52 && self.licence_url == manifest.licence.url
53 }
54}
55
56pub trait AcceptanceStore: Send + Sync {
58 fn acceptances(&self) -> Result<Vec<LicenceAcceptance>>;
64
65 fn record(&self, acceptance: LicenceAcceptance) -> Result<()>;
71}
72
73#[derive(Debug, Default)]
75pub struct InMemoryAcceptanceStore {
76 acceptances: Mutex<Vec<LicenceAcceptance>>,
77}
78
79impl InMemoryAcceptanceStore {
80 pub fn new() -> Self {
82 Self::default()
83 }
84}
85
86impl AcceptanceStore for InMemoryAcceptanceStore {
87 fn acceptances(&self) -> Result<Vec<LicenceAcceptance>> {
88 Ok(self.acceptances.lock().unwrap_or_else(|e| e.into_inner()).clone())
89 }
90
91 fn record(&self, acceptance: LicenceAcceptance) -> Result<()> {
92 self.acceptances.lock().unwrap_or_else(|e| e.into_inner()).push(acceptance);
93 Ok(())
94 }
95}
96
97#[derive(Debug)]
109pub struct FileAcceptanceStore {
110 path: PathBuf,
111 lock: Mutex<()>,
112}
113
114impl FileAcceptanceStore {
115 pub fn new(path: impl Into<PathBuf>) -> Self {
117 Self { path: path.into(), lock: Mutex::new(()) }
118 }
119
120 pub fn in_project(project: &Path) -> Self {
122 Self::new(project.join(".adk").join("vision").join("licences.json"))
123 }
124
125 fn read(&self) -> Result<Vec<LicenceAcceptance>> {
126 match std::fs::read_to_string(&self.path) {
127 Ok(text) => serde_json::from_str(&text).map_err(|e| {
128 VisionError::InvalidInput(format!("{} is not valid: {e}", self.path.display()))
129 }),
130 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
131 Err(err) => Err(VisionError::io("could not read", &self.path, err)),
132 }
133 }
134}
135
136impl AcceptanceStore for FileAcceptanceStore {
137 fn acceptances(&self) -> Result<Vec<LicenceAcceptance>> {
138 let _guard = self.lock.lock().unwrap_or_else(|e| e.into_inner());
139 self.read()
140 }
141
142 fn record(&self, acceptance: LicenceAcceptance) -> Result<()> {
143 let _guard = self.lock.lock().unwrap_or_else(|e| e.into_inner());
144 let mut all = self.read()?;
145 all.push(acceptance);
146 if let Some(parent) = self.path.parent() {
147 std::fs::create_dir_all(parent)
148 .map_err(|e| VisionError::io("could not create", parent, e))?;
149 }
150 let text = serde_json::to_string_pretty(&all)
151 .map_err(|e| VisionError::InvalidInput(e.to_string()))?;
152 let tmp = self.path.with_extension("json.tmp");
153 std::fs::write(&tmp, text).map_err(|e| VisionError::io("could not write", &tmp, e))?;
154 std::fs::rename(&tmp, &self.path)
155 .map_err(|e| VisionError::io("could not replace", &self.path, e))
156 }
157}
158
159#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
161#[serde(rename_all = "camelCase")]
162pub struct LicencePolicy {
163 #[serde(default)]
165 pub allow: BTreeSet<String>,
166}
167
168impl LicencePolicy {
169 pub fn new() -> Self {
171 Self::default()
172 }
173
174 pub fn allowing(mut self, model: impl Into<String>) -> Self {
176 self.allow.insert(model.into());
177 self
178 }
179}
180
181pub struct LicenceGate<'a> {
211 policy: &'a LicencePolicy,
212 acceptances: &'a dyn AcceptanceStore,
213}
214
215impl<'a> LicenceGate<'a> {
216 pub fn new(policy: &'a LicencePolicy, acceptances: &'a dyn AcceptanceStore) -> Self {
218 Self { policy, acceptances }
219 }
220
221 pub fn check(&self, manifest: &ModelManifest) -> Result<()> {
229 match manifest.licence.class {
230 LicenceClass::Permissive => Ok(()),
231 LicenceClass::UseRestricted => {
232 if self.acceptances.acceptances()?.iter().any(|a| a.covers(manifest)) {
233 Ok(())
234 } else {
235 Err(VisionError::LicenceAcceptanceRequired {
236 model: manifest.id.clone(),
237 licence_url: manifest.licence.url.clone(),
238 })
239 }
240 }
241 class @ (LicenceClass::NonCommercial | LicenceClass::Copyleft) => {
242 if self.policy.allow.contains(&manifest.id) {
243 Ok(())
244 } else {
245 Err(VisionError::LicenceNotAllowed {
246 model: manifest.id.clone(),
247 class: class.to_string(),
248 licence_url: manifest.licence.url.clone(),
249 })
250 }
251 }
252 }
253 }
254}