use crate::error::LocalError;
use serde::Deserialize;
use std::collections::HashSet;
use std::sync::OnceLock;
const BUILTIN: &str = include_str!("../catalog/local.toml");
const ID_MAX_BYTES: usize = 64;
const URL_MAX_BYTES: usize = 2_048;
const ROWS_MAX: usize = 256;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DeviceClass {
Phone,
Pi,
#[default]
Desktop,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalSpec {
id: String,
url: String,
sha256: String,
bytes: u64,
ram_bytes: u64,
context: usize,
class: DeviceClass,
licence: String,
embeddings: bool,
recommended: bool,
}
impl LocalSpec {
pub fn new(id: &str, url: &str, sha256: &str, bytes: u64) -> Result<Self, LocalError> {
let id_ok = !id.is_empty()
&& id.len() <= ID_MAX_BYTES
&& !id.starts_with('.')
&& id.bytes().all(|b| {
b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'-' | b'_' | b'.')
});
if !id_ok {
return Err(LocalError::Catalog(format!(
"model id {id:?} is not a valid id"
)));
}
let url_ok = url.len() <= URL_MAX_BYTES
&& url.len() > "https://".len()
&& url.starts_with("https://")
&& !url.bytes().any(|b| b.is_ascii_control() || b == b' ');
if !url_ok {
return Err(LocalError::Catalog(format!(
"model {id}: url must be an https URL"
)));
}
let hash_ok = sha256.len() == 64
&& sha256
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
if !hash_ok {
return Err(LocalError::Catalog(format!(
"model {id}: sha256 must be 64 lowercase hex characters"
)));
}
if bytes == 0 {
return Err(LocalError::Catalog(format!(
"model {id}: bytes must be above 0"
)));
}
Ok(Self {
id: id.to_string(),
url: url.to_string(),
sha256: sha256.to_string(),
bytes,
ram_bytes: bytes,
context: 4_096,
class: DeviceClass::default(),
licence: String::new(),
embeddings: false,
recommended: false,
})
}
pub fn with_ram_bytes(mut self, ram_bytes: u64) -> Self {
self.ram_bytes = ram_bytes;
self
}
pub fn with_context(mut self, context: usize) -> Self {
self.context = context;
self
}
pub fn with_class(mut self, class: DeviceClass) -> Self {
self.class = class;
self
}
pub fn with_licence(mut self, licence: impl Into<String>) -> Self {
self.licence = licence.into();
self
}
pub fn with_embeddings(mut self, embeddings: bool) -> Self {
self.embeddings = embeddings;
self
}
pub fn with_recommended(mut self, recommended: bool) -> Self {
self.recommended = recommended;
self
}
pub fn id(&self) -> &str {
&self.id
}
pub fn url(&self) -> &str {
&self.url
}
pub fn sha256(&self) -> &str {
&self.sha256
}
pub fn bytes(&self) -> u64 {
self.bytes
}
pub fn ram_bytes(&self) -> u64 {
self.ram_bytes
}
pub fn context(&self) -> usize {
self.context
}
pub fn class(&self) -> DeviceClass {
self.class
}
pub fn licence(&self) -> &str {
&self.licence
}
pub fn embeddings(&self) -> bool {
self.embeddings
}
pub fn recommended(&self) -> bool {
self.recommended
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalCatalog {
rows: Vec<LocalSpec>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct File {
#[serde(default)]
model: Vec<Row>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Row {
id: String,
url: String,
sha256: String,
bytes: u64,
ram_bytes: Option<u64>,
context: Option<usize>,
class: Option<DeviceClass>,
licence: Option<String>,
embeddings: Option<bool>,
recommended: Option<bool>,
}
impl LocalCatalog {
pub const MAX_BYTES: usize = 64 * 1024;
pub fn load(text: &str) -> Result<Self, LocalError> {
if text.len() > Self::MAX_BYTES {
return Err(LocalError::Catalog(format!(
"catalog is {} bytes, limit {}",
text.len(),
Self::MAX_BYTES
)));
}
let file: File =
toml::from_str(text).map_err(|e| LocalError::Catalog(e.message().to_string()))?;
let rows = file
.model
.into_iter()
.map(|r| {
let mut spec = LocalSpec::new(&r.id, &r.url, &r.sha256, r.bytes)?;
if let Some(v) = r.ram_bytes {
spec = spec.with_ram_bytes(v);
}
if let Some(v) = r.context {
spec = spec.with_context(v);
}
if let Some(v) = r.class {
spec = spec.with_class(v);
}
if let Some(v) = r.licence {
spec = spec.with_licence(v);
}
Ok(spec
.with_embeddings(r.embeddings.unwrap_or(false))
.with_recommended(r.recommended.unwrap_or(false)))
})
.collect::<Result<Vec<_>, LocalError>>()?;
Self::new(rows)
}
pub fn builtin() -> &'static LocalCatalog {
static CATALOG: OnceLock<LocalCatalog> = OnceLock::new();
CATALOG
.get_or_init(|| Self::load(BUILTIN).expect("the shipped catalog/local.toml is valid"))
}
pub fn new(rows: Vec<LocalSpec>) -> Result<Self, LocalError> {
if rows.len() > ROWS_MAX {
return Err(LocalError::Catalog(format!(
"{} rows, limit {ROWS_MAX}",
rows.len()
)));
}
let mut ids = HashSet::new();
let mut recommended = HashSet::new();
for row in &rows {
if !ids.insert(row.id.as_str()) {
return Err(LocalError::Catalog(format!(
"model id {} appears twice",
row.id
)));
}
if row.recommended && !recommended.insert(row.class) {
return Err(LocalError::Catalog(format!(
"two recommended rows for class {:?}",
row.class
)));
}
}
Ok(Self { rows })
}
pub fn get(&self, id: &str) -> Option<&LocalSpec> {
self.rows.iter().find(|r| r.id == id)
}
pub fn rows(&self) -> &[LocalSpec] {
&self.rows
}
pub fn pick(&self, class: DeviceClass, ram_budget_bytes: u64) -> Option<&LocalSpec> {
let fitting: Vec<&LocalSpec> = self
.rows
.iter()
.filter(|r| r.class == class && r.ram_bytes <= ram_budget_bytes)
.collect();
fitting
.iter()
.find(|r| r.recommended)
.or_else(|| fitting.iter().max_by_key(|r| (r.ram_bytes, r.bytes)))
.copied()
}
}