use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use uuid::Uuid;
use crate::cache::redb::Store;
use crate::cache::{Cache, CachedTarget, SearchHit, RANK_FUZZY};
use crate::error::{Error, ResolveError};
use crate::types::{AliasKind, ResolvedAlias, TargetSource};
use crate::{caldwell, config::ResolverConfig, normalize, Resolver};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UnresolvedReason {
Offline,
Unknown,
Ambiguous,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Resolution {
Resolved(CachedTarget),
Unresolved {
query: String,
reason: UnresolvedReason,
},
}
pub enum CacheBackend {
InMemory,
File(FileCache),
Custom(Arc<dyn Cache>),
}
impl Default for CacheBackend {
fn default() -> Self {
Self::InMemory
}
}
impl CacheBackend {
#[must_use]
pub fn file(path: impl Into<PathBuf>) -> Self {
Self::File(FileCache::new(path))
}
#[must_use]
pub fn custom(cache: impl Cache + 'static) -> Self {
Self::Custom(Arc::new(cache))
}
fn into_cache(self) -> Result<Arc<dyn Cache>, Error> {
match self {
Self::InMemory => Ok(Arc::new(Store::in_memory()?.cache())),
Self::File(f) => Ok(Arc::new(Store::open(f.path)?.cache())),
Self::Custom(c) => Ok(c),
}
}
}
#[derive(Clone, Debug)]
pub struct FileCache {
pub path: PathBuf,
}
impl FileCache {
#[must_use]
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into() }
}
}
pub struct SimbadResolver<R: Resolver> {
resolver: R,
cache: Arc<dyn Cache>,
config: ResolverConfig,
}
impl<R: Resolver> SimbadResolver<R> {
pub fn new(resolver: R, cache: CacheBackend, config: ResolverConfig) -> Result<Self, Error> {
Ok(Self { resolver, cache: cache.into_cache()?, config })
}
pub fn cache(&self) -> &dyn Cache {
self.cache.as_ref()
}
pub fn resolver(&self) -> &R {
&self.resolver
}
pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>, Error> {
let mut hits = self.cache.search(query, limit).await?;
if let Some(min_score) = self.config.fuzzy_min_score {
let q = normalize::normalize(query);
if !q.is_empty() && hits.len() < limit {
let already: HashSet<Uuid> = hits.iter().map(|h| h.target.id).collect();
let mut scored: Vec<(f32, usize, SearchHit)> = Vec::new();
for target in self.cache.list().await? {
if already.contains(&target.id) {
continue;
}
let mut best: Option<(f32, String, usize)> = None;
for alias in &target.aliases {
let score = normalize::jaccard_normalized(&q, &alias.normalized);
if score >= min_score
&& best.as_ref().is_none_or(|(prev, _, _)| score > *prev)
{
best = Some((score, alias.alias.clone(), alias.normalized.len()));
}
}
if let Some((score, matched_alias, normalized_len)) = best {
scored.push((
score,
normalized_len,
SearchHit { target, matched_alias, rank: RANK_FUZZY },
));
}
}
scored.sort_by(|a, b| {
b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)).then_with(|| {
a.2.target.primary_designation.cmp(&b.2.target.primary_designation)
})
});
for (_, _, hit) in scored.into_iter().take(limit - hits.len()) {
hits.push(hit);
}
}
}
Ok(hits)
}
pub async fn resolve(&self, query: &str) -> Result<Resolution, Error> {
resolve_core(&self.resolver, self.cache.as_ref(), &self.config, query).await
}
pub async fn apply_override(
&self,
target_id: Uuid,
alias: &str,
) -> Result<Option<CachedTarget>, Error> {
let Some(existing) = self.cache.get_by_id(target_id).await? else {
return Ok(None);
};
let mut identity = existing.to_identity();
identity.source = TargetSource::UserOverride;
if !alias.trim().is_empty() && !identity.aliases.iter().any(|a| a.alias == alias) {
identity.aliases.push(ResolvedAlias::new(alias.to_owned(), AliasKind::User));
}
let (id, _) = self.cache.upsert(&identity, &self.config.namespace).await?;
Ok(self.cache.get_by_id(id).await?)
}
}
pub(crate) async fn resolve_core<R: Resolver, C: Cache + ?Sized>(
resolver: &R,
cache: &C,
config: &ResolverConfig,
query: &str,
) -> Result<Resolution, Error> {
let (simbad_query, caldwell_alias) = match caldwell::parse_caldwell_number(query) {
Some(n) => match caldwell::caldwell_to_designation(n) {
Some(desig) => (desig.to_owned(), Some(format!("C {n}"))),
None => {
return Ok(Resolution::Unresolved {
query: query.to_owned(),
reason: UnresolvedReason::Unknown,
})
}
},
None => (query.to_owned(), None),
};
for candidate in [normalize::normalize(query), normalize::normalize(&simbad_query)] {
if candidate.is_empty() {
continue;
}
if let Some(target) = cache.get_by_normalized(&candidate).await? {
return Ok(Resolution::Resolved(target));
}
}
if !config.online_enabled {
return Ok(Resolution::Unresolved {
query: query.to_owned(),
reason: UnresolvedReason::Offline,
});
}
match resolver.resolve(&simbad_query).await {
Ok(mut identity) => {
if let Some(c) = &caldwell_alias {
if !identity.aliases.iter().any(|a| &a.alias == c) {
identity.aliases.push(ResolvedAlias::new(c.clone(), AliasKind::Designation));
}
}
let (id, _) = cache.upsert(&identity, &config.namespace).await?;
match cache.get_by_id(id).await? {
Some(target) => Ok(Resolution::Resolved(target)),
None => Ok(Resolution::Unresolved {
query: query.to_owned(),
reason: UnresolvedReason::Unknown,
}),
}
}
Err(e) => Ok(Resolution::Unresolved { query: query.to_owned(), reason: reason_for(&e) }),
}
}
fn reason_for(e: &ResolveError) -> UnresolvedReason {
if e.is_transient() {
UnresolvedReason::Offline
} else if matches!(e, ResolveError::Ambiguous { .. }) {
UnresolvedReason::Ambiguous
} else {
UnresolvedReason::Unknown
}
}