use crate::KanbanBackend;
use kanban_core::AppConfig;
use kanban_domain::KanbanResult;
use std::sync::Arc;
#[async_trait::async_trait]
pub trait KanbanBackendFactory: Send + Sync {
fn name(&self) -> &str;
fn matches_locator(&self, _locator: &str, _header: &[u8]) -> bool {
false
}
fn is_remote(&self) -> bool {
false
}
async fn create(
&self,
locator: &str,
config: &AppConfig,
) -> KanbanResult<Arc<dyn KanbanBackend>>;
}
#[derive(Default)]
pub struct KanbanBackendRegistry {
factories: Vec<Box<dyn KanbanBackendFactory>>,
}
impl KanbanBackendRegistry {
pub fn new() -> Self {
Self {
factories: Vec::new(),
}
}
pub fn register(&mut self, factory: Box<dyn KanbanBackendFactory>) {
self.factories.push(factory);
}
pub fn is_empty(&self) -> bool {
self.factories.is_empty()
}
pub fn names(&self) -> Vec<&str> {
self.factories.iter().map(|f| f.name()).collect()
}
pub fn local_names(&self) -> Vec<&str> {
self.factories
.iter()
.filter(|f| !f.is_remote())
.map(|f| f.name())
.collect()
}
pub fn for_name(&self, name: &str) -> Option<&dyn KanbanBackendFactory> {
self.factories
.iter()
.map(|f| f.as_ref())
.find(|f| f.name() == name)
}
pub fn for_locator(&self, locator: &str) -> Option<&dyn KanbanBackendFactory> {
let header = read_header_best_effort(locator, 32);
self.factories
.iter()
.map(|f| f.as_ref())
.find(|f| f.matches_locator(locator, &header))
}
}
fn read_header_best_effort(locator: &str, n: usize) -> Vec<u8> {
let path = std::path::Path::new(locator);
if !path.exists() {
return Vec::new();
}
let Ok(mut file) = std::fs::File::open(path) else {
return Vec::new();
};
use std::io::Read;
let mut buf = vec![0u8; n];
let read = file.read(&mut buf).unwrap_or(0);
buf.truncate(read);
buf
}