Skip to main content

simbad_resolver/
orchestrate.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Cache-first single resolution + sticky user override.
6
7use std::collections::HashSet;
8use std::path::PathBuf;
9use std::sync::Arc;
10
11use uuid::Uuid;
12
13use crate::cache::redb::Store;
14use crate::cache::{Cache, CachedTarget, SearchHit, RANK_FUZZY};
15use crate::error::{Error, ResolveError};
16use crate::types::{AliasKind, ResolvedAlias, TargetSource};
17use crate::{caldwell, config::ResolverConfig, normalize, Resolver};
18
19/// Why a query could not be resolved to a canonical target.
20///
21/// ```
22/// use simbad_resolver::UnresolvedReason;
23///
24/// // A transient failure and a genuine content miss both leave a query
25/// // `Unresolved`, but a caller acts on them differently.
26/// assert!(matches!(UnresolvedReason::Offline, UnresolvedReason::Offline));
27/// let content_miss = UnresolvedReason::Unknown;
28/// assert_ne!(content_miss, UnresolvedReason::Offline);
29/// ```
30#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31pub enum UnresolvedReason {
32    /// The online resolver was unreachable/timed out/disabled; the caller may
33    /// retry later. Cached/known objects still resolve.
34    Offline,
35    /// The query is unknown (no such object) or malformed.
36    Unknown,
37    /// The query maps to several distinct physical objects.
38    Ambiguous,
39}
40
41/// The outcome of a [`SimbadResolver::resolve`] call.
42///
43/// ```
44/// use simbad_resolver::{Resolution, UnresolvedReason};
45///
46/// let outcome = Resolution::Unresolved {
47///     query: "not-a-real-object".to_owned(),
48///     reason: UnresolvedReason::Unknown,
49/// };
50/// match outcome {
51///     Resolution::Resolved(target) => println!("{}", target.primary_designation),
52///     Resolution::Unresolved { query, reason } => {
53///         println!("{query} did not resolve: {reason:?}");
54///     }
55/// }
56/// ```
57#[derive(Clone, Debug, PartialEq)]
58pub enum Resolution {
59    /// A canonical target (from cache or freshly resolved + cached).
60    Resolved(CachedTarget),
61    /// No canonical target was found; see [`UnresolvedReason`] for why.
62    Unresolved {
63        /// The verbatim query.
64        query: String,
65        /// Why it is unresolved.
66        reason: UnresolvedReason,
67    },
68}
69
70/// How a [`SimbadResolver`] obtains its cache backend.
71///
72/// The built-in variants select the redb-backed [`Store`](crate::Store) at
73/// construction; [`Custom`](Self::Custom) accepts any [`Cache`]. Backend tuning
74/// lives on the variant that owns it (e.g. [`FileCache`]), so the constructor
75/// signature never grows.
76///
77/// There is deliberately no "disabled" variant: the cache is load-bearing (the
78/// resolve pipeline returns cached rows), so [`InMemory`](Self::InMemory) is the
79/// ephemeral, nothing-persisted choice and is what [`Default`] selects. For a
80/// truly uncached one-shot lookup, call a bare [`Resolver`] directly instead of
81/// the facade.
82///
83/// ```
84/// use simbad_resolver::CacheBackend;
85///
86/// let ephemeral = CacheBackend::InMemory;
87/// let durable = CacheBackend::file("targets.redb"); // opened lazily by `SimbadResolver::new`
88/// assert!(matches!(ephemeral, CacheBackend::InMemory));
89/// assert!(matches!(durable, CacheBackend::File(_)));
90/// ```
91pub enum CacheBackend {
92    /// Ephemeral in-memory redb store (nothing persisted to disk).
93    InMemory,
94    /// Durable, file-backed redb store.
95    File(FileCache),
96    /// A caller-supplied cache backend.
97    Custom(Arc<dyn Cache>),
98}
99
100impl Default for CacheBackend {
101    /// The zero-config default: an ephemeral in-memory store.
102    fn default() -> Self {
103        Self::InMemory
104    }
105}
106
107impl CacheBackend {
108    /// A file-backed backend at `path` with default options.
109    ///
110    /// ```
111    /// use simbad_resolver::CacheBackend;
112    ///
113    /// let backend = CacheBackend::file("targets.redb"); // opened lazily by `SimbadResolver::new`
114    /// assert!(matches!(backend, CacheBackend::File(_)));
115    /// ```
116    #[must_use]
117    pub fn file(path: impl Into<PathBuf>) -> Self {
118        Self::File(FileCache::new(path))
119    }
120
121    /// Wrap a caller-supplied cache backend.
122    ///
123    /// ```
124    /// use simbad_resolver::{CacheBackend, Store};
125    ///
126    /// # fn run() -> Result<(), simbad_resolver::CacheError> {
127    /// // Any `Cache` impl works, e.g. a `Store`'s own `.cache()`.
128    /// let backend = CacheBackend::custom(Store::in_memory()?.cache());
129    /// assert!(matches!(backend, CacheBackend::Custom(_)));
130    /// # Ok(()) }
131    /// ```
132    #[must_use]
133    pub fn custom(cache: impl Cache + 'static) -> Self {
134        Self::Custom(Arc::new(cache))
135    }
136
137    /// Materialise the selection into a shared [`Cache`] handle.
138    fn into_cache(self) -> Result<Arc<dyn Cache>, Error> {
139        match self {
140            Self::InMemory => Ok(Arc::new(Store::in_memory()?.cache())),
141            Self::File(f) => Ok(Arc::new(Store::open(f.path)?.cache())),
142            Self::Custom(c) => Ok(c),
143        }
144    }
145}
146
147/// Options for the built-in file-backed cache.
148///
149/// Future tunables (cache size, durability, …) are added here, defaulted —
150/// never as new constructor arguments.
151#[derive(Clone, Debug)]
152pub struct FileCache {
153    /// Path to the redb database file (created if missing).
154    pub path: PathBuf,
155}
156
157impl FileCache {
158    /// A file cache at `path` with default options.
159    ///
160    /// ```
161    /// use simbad_resolver::FileCache;
162    ///
163    /// let file_cache = FileCache::new("targets.redb");
164    /// assert_eq!(file_cache.path.to_str(), Some("targets.redb"));
165    /// ```
166    #[must_use]
167    pub fn new(path: impl Into<PathBuf>) -> Self {
168        Self { path: path.into() }
169    }
170}
171
172/// The cache-first resolver facade.
173///
174/// Generic over any [`Resolver`] backend (TAP, Sesame, offline, fake); the cache
175/// backend is chosen at construction via [`CacheBackend`] and type-erased, so
176/// the facade type does not carry it.
177///
178/// This example uses [`crate::OfflineResolver`] and seeds the cache directly, so
179/// it runs without a network call — the cache-first lookup below never reaches
180/// the resolver.
181///
182/// ```
183/// use simbad_resolver::{
184///     AliasKind, CacheBackend, OfflineResolver, ObjectType, Resolution, ResolvedAlias,
185///     ResolvedIdentity, ResolverConfig, SimbadResolver, TargetSource,
186/// };
187///
188/// # async fn demo() -> Result<(), simbad_resolver::Error> {
189/// let config = ResolverConfig::new("guide.example");
190/// let namespace = config.namespace;
191/// let facade = SimbadResolver::new(OfflineResolver, CacheBackend::InMemory, config)?;
192///
193/// let m31 = ResolvedIdentity {
194///     simbad_oid: Some(1_575_544),
195///     primary_designation: "M 31".to_owned(),
196///     common_name: Some("Andromeda Galaxy".to_owned()),
197///     object_type: ObjectType::Galaxy,
198///     otype_raw: "G".to_owned(),
199///     ra_deg: 10.684_708,
200///     dec_deg: 41.268_75,
201///     v_mag: Some(3.44),
202///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
203///     source: TargetSource::Seed,
204/// };
205/// facade.cache().upsert(&m31, &namespace).await?;
206///
207/// match facade.resolve("M31").await? {
208///     Resolution::Resolved(target) => assert_eq!(target.primary_designation, "M 31"),
209///     Resolution::Unresolved { .. } => unreachable!("seeded above"),
210/// }
211/// # Ok(()) }
212/// ```
213pub struct SimbadResolver<R: Resolver> {
214    resolver: R,
215    cache: Arc<dyn Cache>,
216    config: ResolverConfig,
217}
218
219impl<R: Resolver> SimbadResolver<R> {
220    /// Construct a facade from a resolver, a [`CacheBackend`], and config.
221    ///
222    /// # Errors
223    ///
224    /// Returns [`Error`] if a built-in ([`CacheBackend::InMemory`] /
225    /// [`CacheBackend::File`]) store cannot be opened or initialised.
226    /// [`CacheBackend::Custom`] never fails here.
227    ///
228    /// ```
229    /// use simbad_resolver::{CacheBackend, OfflineResolver, ResolverConfig, SimbadResolver};
230    ///
231    /// let facade = SimbadResolver::new(
232    ///     OfflineResolver,
233    ///     CacheBackend::InMemory,
234    ///     ResolverConfig::new("my-app.targets"),
235    /// )?;
236    /// # let _ = facade;
237    /// # Ok::<(), simbad_resolver::Error>(())
238    /// ```
239    pub fn new(resolver: R, cache: CacheBackend, config: ResolverConfig) -> Result<Self, Error> {
240        Ok(Self { resolver, cache: cache.into_cache()?, config })
241    }
242
243    /// Borrow the underlying cache (e.g. for seeding or enumeration).
244    ///
245    /// ```
246    /// use simbad_resolver::{CacheBackend, OfflineResolver, ResolverConfig, SimbadResolver};
247    ///
248    /// # async fn run() -> Result<(), simbad_resolver::Error> {
249    /// let facade =
250    ///     SimbadResolver::new(OfflineResolver, CacheBackend::InMemory, ResolverConfig::new("x"))?;
251    /// assert!(facade.cache().list().await?.is_empty(), "freshly constructed cache is empty");
252    /// # Ok(()) }
253    /// ```
254    pub fn cache(&self) -> &dyn Cache {
255        self.cache.as_ref()
256    }
257
258    /// Borrow the underlying resolver (e.g. to inspect a fake's call count in tests).
259    ///
260    /// ```
261    /// use simbad_resolver::{CacheBackend, OfflineResolver, ResolverConfig, SimbadResolver};
262    ///
263    /// let facade =
264    ///     SimbadResolver::new(OfflineResolver, CacheBackend::InMemory, ResolverConfig::new("x"))?;
265    /// let _resolver: &OfflineResolver = facade.resolver();
266    /// # Ok::<(), simbad_resolver::Error>(())
267    /// ```
268    pub fn resolver(&self) -> &R {
269        &self.resolver
270    }
271
272    /// Local, network-free typeahead search over cached aliases.
273    ///
274    /// Returns exact/prefix/substring matches (see [`Cache::search`]). When fuzzy
275    /// matching is enabled via [`ResolverConfig::with_fuzzy`] and fewer than
276    /// `limit` of those are found, the remaining slots are filled with token-set
277    /// similarity matches ([`crate::RANK_FUZZY`]), best score first. This fuzzy
278    /// matching does not affect [`Self::resolve`], which stays exact-normalized.
279    ///
280    /// This example seeds the cache directly (no resolver call needed) then
281    /// searches it — see [the guide](crate::guide) for the full walkthrough.
282    ///
283    /// ```
284    /// use simbad_resolver::{
285    ///     AliasKind, CacheBackend, ObjectType, OfflineResolver, ResolvedAlias, ResolvedIdentity,
286    ///     ResolverConfig, SimbadResolver, TargetSource,
287    /// };
288    ///
289    /// # async fn run() -> Result<(), simbad_resolver::Error> {
290    /// let config = ResolverConfig::new("example");
291    /// let namespace = config.namespace;
292    /// let facade = SimbadResolver::new(OfflineResolver, CacheBackend::InMemory, config)?;
293    /// let m31 = ResolvedIdentity {
294    ///     simbad_oid: Some(1_575_544),
295    ///     primary_designation: "M 31".to_owned(),
296    ///     common_name: None,
297    ///     object_type: ObjectType::Galaxy,
298    ///     otype_raw: "G".to_owned(),
299    ///     ra_deg: 10.684_708,
300    ///     dec_deg: 41.268_75,
301    ///     v_mag: Some(3.44),
302    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
303    ///     source: TargetSource::Seed,
304    /// };
305    /// facade.cache().upsert(&m31, &namespace).await?;
306    ///
307    /// let hits = facade.search("M 3", 5).await?; // prefix match
308    /// assert_eq!(hits[0].target.primary_designation, "M 31");
309    /// # Ok(()) }
310    /// ```
311    pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>, Error> {
312        let mut hits = self.cache.search(query, limit).await?;
313
314        if let Some(min_score) = self.config.fuzzy_min_score {
315            let q = normalize::normalize(query);
316            if !q.is_empty() && hits.len() < limit {
317                let already: HashSet<Uuid> = hits.iter().map(|h| h.target.id).collect();
318
319                // Score each not-yet-matched target by its best-matching alias.
320                let mut scored: Vec<(f32, usize, SearchHit)> = Vec::new();
321                for target in self.cache.list().await? {
322                    if already.contains(&target.id) {
323                        continue;
324                    }
325                    let mut best: Option<(f32, String, usize)> = None;
326                    for alias in &target.aliases {
327                        let score = normalize::jaccard_normalized(&q, &alias.normalized);
328                        if score >= min_score
329                            && best.as_ref().is_none_or(|(prev, _, _)| score > *prev)
330                        {
331                            best = Some((score, alias.alias.clone(), alias.normalized.len()));
332                        }
333                    }
334                    if let Some((score, matched_alias, normalized_len)) = best {
335                        scored.push((
336                            score,
337                            normalized_len,
338                            SearchHit { target, matched_alias, rank: RANK_FUZZY },
339                        ));
340                    }
341                }
342
343                // Best score first; ties break on the shorter matched alias, then
344                // the target's primary designation (stable, deterministic order).
345                scored.sort_by(|a, b| {
346                    b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)).then_with(|| {
347                        a.2.target.primary_designation.cmp(&b.2.target.primary_designation)
348                    })
349                });
350                for (_, _, hit) in scored.into_iter().take(limit - hits.len()) {
351                    hits.push(hit);
352                }
353            }
354        }
355
356        Ok(hits)
357    }
358
359    /// Cache-first resolve. On a cache miss and when online is enabled, consult
360    /// the resolver, persist the result, and return it; otherwise return a typed
361    /// [`Resolution::Unresolved`]. Caldwell designations (`C n`) are translated
362    /// to their standard designation first and the original `C n` bound as an
363    /// alias.
364    ///
365    /// See the [struct-level example](Self) for a seeded, network-free
366    /// walkthrough, or [`crate::guide`] for the full task-oriented guide.
367    ///
368    /// ```
369    /// use simbad_resolver::{CacheBackend, OfflineResolver, Resolution, ResolverConfig, SimbadResolver};
370    ///
371    /// # async fn run() -> Result<(), simbad_resolver::Error> {
372    /// let facade =
373    ///     SimbadResolver::new(OfflineResolver, CacheBackend::InMemory, ResolverConfig::new("x"))?;
374    /// // Nothing cached and no network reachable (`OfflineResolver`): unresolved, not an error.
375    /// match facade.resolve("M31").await? {
376    ///     Resolution::Resolved(_) => unreachable!("cache is empty"),
377    ///     Resolution::Unresolved { query, .. } => assert_eq!(query, "M31"),
378    /// }
379    /// # Ok(()) }
380    /// ```
381    pub async fn resolve(&self, query: &str) -> Result<Resolution, Error> {
382        resolve_core(&self.resolver, self.cache.as_ref(), &self.config, query).await
383    }
384
385    /// Bind a chosen canonical target as an authoritative user override, adding
386    /// `alias` and making the row sticky (`source = user-override`). Returns the
387    /// updated target, or `None` if `target_id` is unknown.
388    ///
389    /// See [`crate::guide`] for a full "pin a target" walkthrough.
390    ///
391    /// ```
392    /// use simbad_resolver::{
393    ///     AliasKind, CacheBackend, ObjectType, OfflineResolver, ResolvedAlias, ResolvedIdentity,
394    ///     ResolverConfig, SimbadResolver, TargetSource,
395    /// };
396    ///
397    /// # async fn run() -> Result<(), simbad_resolver::Error> {
398    /// let config = ResolverConfig::new("example");
399    /// let namespace = config.namespace;
400    /// let facade = SimbadResolver::new(OfflineResolver, CacheBackend::InMemory, config)?;
401    /// let m31 = ResolvedIdentity {
402    ///     simbad_oid: Some(1_575_544),
403    ///     primary_designation: "M 31".to_owned(),
404    ///     common_name: None,
405    ///     object_type: ObjectType::Galaxy,
406    ///     otype_raw: "G".to_owned(),
407    ///     ra_deg: 10.684_708,
408    ///     dec_deg: 41.268_75,
409    ///     v_mag: Some(3.44),
410    ///     aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
411    ///     source: TargetSource::Seed,
412    /// };
413    /// let (id, _) = facade.cache().upsert(&m31, &namespace).await?;
414    ///
415    /// let pinned = facade.apply_override(id, "My Andromeda").await?.expect("id is known");
416    /// assert_eq!(pinned.source, TargetSource::UserOverride);
417    /// assert!(pinned.aliases.iter().any(|a| a.alias == "My Andromeda"));
418    /// # Ok(()) }
419    /// ```
420    pub async fn apply_override(
421        &self,
422        target_id: Uuid,
423        alias: &str,
424    ) -> Result<Option<CachedTarget>, Error> {
425        let Some(existing) = self.cache.get_by_id(target_id).await? else {
426            return Ok(None);
427        };
428        let mut identity = existing.to_identity();
429        identity.source = TargetSource::UserOverride;
430        if !alias.trim().is_empty() && !identity.aliases.iter().any(|a| a.alias == alias) {
431            identity.aliases.push(ResolvedAlias::new(alias.to_owned(), AliasKind::User));
432        }
433        let (id, _) = self.cache.upsert(&identity, &self.config.namespace).await?;
434        Ok(self.cache.get_by_id(id).await?)
435    }
436}
437
438/// The shared cache-first resolve routine used by both the facade and the batch
439/// resolver. Caldwell-translates, checks the cache, then (if online) resolves,
440/// persists, and re-reads.
441pub(crate) async fn resolve_core<R: Resolver, C: Cache + ?Sized>(
442    resolver: &R,
443    cache: &C,
444    config: &ResolverConfig,
445    query: &str,
446) -> Result<Resolution, Error> {
447    // Caldwell translation (facade-level so it applies to any resolver).
448    let (simbad_query, caldwell_alias) = match caldwell::parse_caldwell_number(query) {
449        Some(n) => match caldwell::caldwell_to_designation(n) {
450            Some(desig) => (desig.to_owned(), Some(format!("C {n}"))),
451            None => {
452                return Ok(Resolution::Unresolved {
453                    query: query.to_owned(),
454                    reason: UnresolvedReason::Unknown,
455                })
456            }
457        },
458        None => (query.to_owned(), None),
459    };
460
461    // Cache-first: try the original query, then the translated designation.
462    for candidate in [normalize::normalize(query), normalize::normalize(&simbad_query)] {
463        if candidate.is_empty() {
464            continue;
465        }
466        if let Some(target) = cache.get_by_normalized(&candidate).await? {
467            return Ok(Resolution::Resolved(target));
468        }
469    }
470
471    if !config.online_enabled {
472        return Ok(Resolution::Unresolved {
473            query: query.to_owned(),
474            reason: UnresolvedReason::Offline,
475        });
476    }
477
478    match resolver.resolve(&simbad_query).await {
479        Ok(mut identity) => {
480            if let Some(c) = &caldwell_alias {
481                if !identity.aliases.iter().any(|a| &a.alias == c) {
482                    identity.aliases.push(ResolvedAlias::new(c.clone(), AliasKind::Designation));
483                }
484            }
485            let (id, _) = cache.upsert(&identity, &config.namespace).await?;
486            match cache.get_by_id(id).await? {
487                Some(target) => Ok(Resolution::Resolved(target)),
488                None => Ok(Resolution::Unresolved {
489                    query: query.to_owned(),
490                    reason: UnresolvedReason::Unknown,
491                }),
492            }
493        }
494        Err(e) => Ok(Resolution::Unresolved { query: query.to_owned(), reason: reason_for(&e) }),
495    }
496}
497
498/// Map a resolver error to an unresolved reason (transient → Offline).
499fn reason_for(e: &ResolveError) -> UnresolvedReason {
500    if e.is_transient() {
501        UnresolvedReason::Offline
502    } else if matches!(e, ResolveError::Ambiguous { .. }) {
503        UnresolvedReason::Ambiguous
504    } else {
505        UnresolvedReason::Unknown
506    }
507}