use std::sync::{Arc, LazyLock};
use futures::future::BoxFuture;
use parking_lot::RwLock;
use regex::Regex;
use crate::{Llm, ModelError};
pub type Factory =
Arc<dyn Fn(String) -> BoxFuture<'static, Result<Arc<dyn Llm>, ModelError>> + Send + Sync>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum RegistryError {
#[error("model: invalid LLM pattern {0:?}: {1}")]
InvalidPattern(String, String),
#[error("model: LLM pattern {0:?} is already registered")]
DuplicatePattern(String),
#[error("model: no registered LLM matches {0:?}")]
NoMatch(String),
#[error(
"model: {name:?} matches multiple registered LLM patterns {patterns:?}; patterns must be unambiguous"
)]
Ambiguous {
name: String,
patterns: Vec<String>,
},
#[error(transparent)]
Factory(ModelError),
}
struct Registration {
regex: Regex,
pattern: String,
factory: Factory,
}
#[derive(Default)]
pub struct Registry {
entries: RwLock<Vec<Registration>>,
}
static GLOBAL: LazyLock<Registry> = LazyLock::new(Registry::new);
impl Registry {
pub fn new() -> Self {
Self::default()
}
pub fn global() -> &'static Registry {
&GLOBAL
}
pub fn register(&self, pattern: &str, f: Factory) -> Result<(), RegistryError> {
let regex = Regex::new(pattern)
.map_err(|e| RegistryError::InvalidPattern(pattern.to_string(), e.to_string()))?;
let mut entries = self.entries.write();
if entries.iter().any(|r| r.pattern == pattern) {
return Err(RegistryError::DuplicatePattern(pattern.to_string()));
}
entries.push(Registration {
regex,
pattern: pattern.to_string(),
factory: f,
});
Ok(())
}
pub async fn new_llm(&self, name: &str) -> Result<Arc<dyn Llm>, RegistryError> {
let (factory, matched) = {
let entries = self.entries.read();
let mut factory = None;
let mut matched = Vec::new();
for r in entries.iter().filter(|r| r.regex.is_match(name)) {
factory = Some(r.factory.clone());
matched.push(r.pattern.clone());
}
(factory, matched)
};
match (factory, matched.len()) {
(Some(f), 1) => f(name.to_string()).await.map_err(RegistryError::Factory),
(_, 0) | (None, _) => Err(RegistryError::NoMatch(name.to_string())),
_ => Err(RegistryError::Ambiguous {
name: name.to_string(),
patterns: matched,
}),
}
}
}