Skip to main content

aspero_engine/
lib.rs

1//! Routing, caching, merging and resilience over registered providers.
2//!
3//! The engine owns what providers deliberately don't: retries and backoff
4//! ([`retry`]), request pacing and the real HTTP client ([`transport`]), and
5//! choosing which provider answers what.
6//!
7//! - **Lookup** is interchangeable across providers: each ID goes to the
8//!   providers that accept its kind, in priority order, until one finds it.
9//!   A provider that doesn't know an ID or fails falls through to the next;
10//!   every attempt is reported.
11//! - **Search** is not interchangeable (rankings differ), so it runs against
12//!   one provider: the one named, or the first capable one. Filters that
13//!   provider doesn't declare are stripped and reported as ignored, never
14//!   silently dropped.
15//!
16//! - **Resolve / verify** turn a citation claim into scored candidates and a
17//!   verdict (see [`resolve`](crate::Engine::resolve)).
18//!
19//! - **Caching**: provider answers (records, "not found", search pages) are
20//!   cached with per-kind TTLs ([`CachePolicy`]) and served stale if a
21//!   provider fails; every answer says how it was [`Served`].
22//!
23//! Not yet: fan-out search, the circuit breaker and the cross-process
24//! limiter.
25
26mod abstracts;
27mod check;
28mod resolve;
29pub mod retry;
30mod standard;
31pub mod transport;
32
33pub use abstracts::{Abstract, AbstractsReport};
34pub use check::{Checked, Finding, Severity, duplicates, findings};
35pub use resolve::{
36    Candidate, ResolveReport, Sighting, Verdict, Verification, Via, describe_update,
37};
38/// Re-exported for credentials in provider configs.
39pub use secrecy::SecretString;
40#[cfg(feature = "crossref")]
41pub use standard::CrossrefConfig;
42#[cfg(feature = "datacite")]
43pub use standard::DataciteConfig;
44#[cfg(feature = "doi")]
45pub use standard::DoiConfig;
46#[cfg(feature = "europepmc")]
47pub use standard::EuropePmcConfig;
48#[cfg(feature = "openalex")]
49pub use standard::OpenAlexConfig;
50#[cfg(feature = "openlibrary")]
51pub use standard::OpenLibraryConfig;
52pub use standard::{StandardConfig, standard};
53
54use std::sync::Arc;
55use std::time::Duration;
56
57use aspero_core::{
58    Error, ErrorCategory, FieldSet, Filter, Page, Provider, ProviderId, ResiliencePolicy,
59    SearchMode, SearchQuery, SourceRecord, Usage, WorkId,
60};
61pub use aspero_store::{Cache, SqliteCache, Stats as CacheStats, StoreError};
62use jiff::Timestamp;
63
64use crate::retry::{Jitter, random_jitter, with_retries};
65
66/// A clock, injectable so cache expiry is testable.
67pub type Clock = fn() -> Timestamp;
68
69/// How long cached answers are trusted (DESIGN ยง5). Past these, a provider
70/// is asked again; if it then fails, the old answer is served as stale.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72#[non_exhaustive]
73pub struct CachePolicy {
74    pub records: Duration,
75    /// "Not found" answers: short, since works get registered.
76    pub misses: Duration,
77    pub searches: Duration,
78}
79
80impl Default for CachePolicy {
81    fn default() -> Self {
82        const DAY: u64 = 86_400;
83        CachePolicy {
84            records: Duration::from_secs(7 * DAY),
85            misses: Duration::from_secs(DAY),
86            searches: Duration::from_secs(DAY),
87        }
88    }
89}
90
91/// Where an answer came from.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum Served {
95    Live,
96    /// A cached answer within its TTL.
97    Cache,
98    /// An expired cached answer, served because the provider failed.
99    Stale,
100}
101
102impl Served {
103    pub fn as_str(self) -> &'static str {
104        match self {
105            Served::Live => "live",
106            Served::Cache => "cache",
107            Served::Stale => "stale",
108        }
109    }
110}
111
112pub struct Engine {
113    /// In priority order.
114    entries: Vec<Entry>,
115    jitter: Jitter,
116    cache: Option<Arc<dyn Cache>>,
117    cache_policy: CachePolicy,
118    clock: Clock,
119}
120
121struct Entry {
122    provider: Arc<dyn Provider>,
123    policy: ResiliencePolicy,
124}
125
126pub struct EngineBuilder {
127    entries: Vec<(i32, Entry)>,
128    jitter: Jitter,
129    cache: Option<Arc<dyn Cache>>,
130    cache_policy: CachePolicy,
131    clock: Clock,
132}
133
134impl EngineBuilder {
135    /// Registers a provider. Lower `priority` is tried first; ties keep
136    /// registration order.
137    pub fn provider(
138        mut self,
139        provider: Arc<dyn Provider>,
140        policy: ResiliencePolicy,
141        priority: i32,
142    ) -> Self {
143        self.entries.push((priority, Entry { provider, policy }));
144        self
145    }
146
147    /// Replaces the backoff jitter source (for deterministic tests).
148    pub fn jitter(mut self, jitter: Jitter) -> Self {
149        self.jitter = jitter;
150        self
151    }
152
153    /// Caches provider answers (and serves them stale if a provider fails).
154    pub fn cache(mut self, cache: Arc<dyn Cache>) -> Self {
155        self.cache = Some(cache);
156        self
157    }
158
159    pub fn cache_policy(mut self, policy: CachePolicy) -> Self {
160        self.cache_policy = policy;
161        self
162    }
163
164    /// Replaces the clock (for deterministic cache-expiry tests).
165    pub fn clock(mut self, clock: Clock) -> Self {
166        self.clock = clock;
167        self
168    }
169
170    pub fn build(mut self) -> Engine {
171        self.entries.sort_by_key(|(priority, _)| *priority);
172        Engine {
173            entries: self.entries.into_iter().map(|(_, e)| e).collect(),
174            jitter: self.jitter,
175            cache: self.cache,
176            cache_policy: self.cache_policy,
177            clock: self.clock,
178        }
179    }
180}
181
182/// The outcome of one provider's attempt at one ID.
183#[derive(Debug, Clone)]
184#[non_exhaustive]
185pub enum Outcome {
186    Found,
187    NotFound,
188    Failed(Error),
189}
190
191#[derive(Debug, Clone)]
192pub struct Attempt {
193    pub provider: ProviderId,
194    pub outcome: Outcome,
195    pub served: Served,
196}
197
198#[derive(Debug, Clone)]
199pub struct LookupResult {
200    /// As requested.
201    pub id: WorkId,
202    pub record: Option<SourceRecord>,
203    /// Every provider tried, in order. Empty: no enabled provider accepts
204    /// this kind of identifier.
205    pub attempts: Vec<Attempt>,
206}
207
208impl LookupResult {
209    /// No provider found it, and at least one could answer authoritatively
210    /// (rather than every attempt failing).
211    pub fn is_not_found(&self) -> bool {
212        self.record.is_none()
213            && self
214                .attempts
215                .iter()
216                .any(|a| matches!(a.outcome, Outcome::NotFound))
217    }
218}
219
220#[derive(Debug, Clone)]
221pub struct LookupReport {
222    /// One per requested ID, in request order.
223    pub results: Vec<LookupResult>,
224    /// Combined usage per provider that reported any.
225    pub usage: Vec<(ProviderId, Usage)>,
226}
227
228#[derive(Debug, Clone)]
229pub struct SearchReport {
230    pub provider: ProviderId,
231    pub page: Page,
232    /// Query filters the provider can't apply; they were not sent.
233    pub ignored_filters: Vec<Filter>,
234    pub usage: Option<Usage>,
235    pub served: Served,
236}
237
238#[derive(Debug, Clone, thiserror::Error)]
239#[non_exhaustive]
240pub enum EngineError {
241    #[error("no enabled provider is named {0:?}")]
242    UnknownProvider(String),
243    #[error("no enabled provider supports {0}")]
244    NoCapableProvider(&'static str),
245    #[error("{provider}: {error}")]
246    Provider {
247        provider: ProviderId,
248        #[source]
249        error: Error,
250    },
251}
252
253impl EngineError {
254    pub fn category(&self) -> ErrorCategory {
255        match self {
256            EngineError::UnknownProvider(_) => ErrorCategory::Usage,
257            EngineError::NoCapableProvider(_) => ErrorCategory::Unsupported,
258            EngineError::Provider { error, .. } => error.category(),
259        }
260    }
261}
262
263impl Engine {
264    pub fn builder() -> EngineBuilder {
265        EngineBuilder {
266            entries: Vec::new(),
267            jitter: random_jitter,
268            cache: None,
269            cache_policy: CachePolicy::default(),
270            clock: Timestamp::now,
271        }
272    }
273
274    /// Registered providers, in priority order.
275    pub fn providers(&self) -> impl Iterator<Item = &Arc<dyn Provider>> {
276        self.entries.iter().map(|e| &e.provider)
277    }
278
279    /// Looks up every ID, falling through providers by priority. Never fails
280    /// as a whole: per-ID outcomes are in the report.
281    pub async fn lookup(&self, ids: &[WorkId], fields: FieldSet) -> LookupReport {
282        let mut results: Vec<LookupResult> = ids
283            .iter()
284            .map(|id| LookupResult {
285                id: id.clone(),
286                record: None,
287                attempts: Vec::new(),
288            })
289            .collect();
290        let mut usage: Vec<(ProviderId, Usage)> = Vec::new();
291
292        for entry in &self.entries {
293            let caps = entry.provider.capabilities();
294            let eligible: Vec<usize> = (0..results.len())
295                .filter(|&i| results[i].record.is_none())
296                .filter(|&i| caps.lookup_kinds.contains(&results[i].id.kind()))
297                .collect();
298            let ids: Vec<WorkId> = eligible.iter().map(|&i| results[i].id.clone()).collect();
299            let answers = self.lookup_at(entry, &ids, fields, &mut usage).await;
300            for (&i, (attempt, record)) in eligible.iter().zip(answers) {
301                results[i].record = record;
302                results[i].attempts.push(attempt);
303            }
304        }
305        LookupReport { results, usage }
306    }
307
308    /// Adds editorial notices, in both directions, to records that another
309    /// provider supplied, from the providers that report them in detail
310    /// (Crossref): an original then lists its corrections and retractions,
311    /// a correction the work it corrects. Batched and cached, like lookups.
312    pub async fn add_notices(&self, report: &mut LookupReport) {
313        for entry in &self.entries {
314            let caps = entry.provider.capabilities();
315            if !caps.notices {
316                continue;
317            }
318            let provider = entry.provider.id();
319            let wanted: Vec<(usize, WorkId)> = report
320                .results
321                .iter()
322                .enumerate()
323                .filter_map(|(i, r)| {
324                    let record = r.record.as_ref().filter(|r| r.source != provider)?;
325                    let id = record
326                        .ids
327                        .iter()
328                        .find(|id| caps.lookup_kinds.contains(&id.kind()))?;
329                    Some((i, id.clone()))
330                })
331                .collect();
332            if wanted.is_empty() {
333                continue;
334            }
335            let ids: Vec<WorkId> = wanted.iter().map(|(_, id)| id.clone()).collect();
336            let answers = self
337                .lookup_at(entry, &ids, FieldSet::ALL, &mut report.usage)
338                .await;
339            for ((i, _), (_, found)) in wanted.into_iter().zip(answers) {
340                let (Some(found), Some(record)) = (found, report.results[i].record.as_mut()) else {
341                    continue;
342                };
343                let work = &mut record.work;
344                resolve::merge_updates(&mut work.updates, &found.work.updates);
345                for target in found.work.update_to {
346                    if !work.update_to.contains(&target) {
347                        work.update_to.push(target);
348                    }
349                }
350            }
351        }
352    }
353
354    /// Asks one provider about `ids` (all of kinds it accepts): fresh cached
355    /// answers first, the rest in batches with retries, and stale cached
356    /// records for any that fail. One answer per ID, in order.
357    async fn lookup_at(
358        &self,
359        entry: &Entry,
360        ids: &[WorkId],
361        fields: FieldSet,
362        usage: &mut Vec<(ProviderId, Usage)>,
363    ) -> Vec<(Attempt, Option<SourceRecord>)> {
364        let provider = entry.provider.id();
365        let caps = entry.provider.capabilities();
366        let attempt = |outcome, served| Attempt {
367            provider: provider.clone(),
368            outcome,
369            served,
370        };
371        let mut answers: Vec<Option<(Attempt, Option<SourceRecord>)>> = vec![None; ids.len()];
372
373        // Fresh cached answers first (one cache read for the whole set).
374        let mut pending = Vec::new();
375        let mut from_cache = 0;
376        for (i, cached) in self
377            .cached_lookups(&provider, ids, fields)
378            .into_iter()
379            .enumerate()
380        {
381            answers[i] = match cached {
382                Some(Some(record)) => {
383                    from_cache += 1;
384                    Some((attempt(Outcome::Found, Served::Cache), Some(record)))
385                }
386                Some(None) => {
387                    from_cache += 1;
388                    Some((attempt(Outcome::NotFound, Served::Cache), None))
389                }
390                None => {
391                    pending.push(i);
392                    None
393                }
394            };
395        }
396
397        if from_cache > 0 {
398            tracing::info!(target: "aspero::cache", provider = %provider, ids = from_cache, "lookups served from cache");
399        }
400        let mut chunks = pending.chunks(caps.max_batch.max(1));
401        while let Some(chunk) = chunks.next() {
402            let batch: Vec<WorkId> = chunk.iter().map(|&i| ids[i].clone()).collect();
403            let answer = with_retries(&entry.policy, self.jitter, || {
404                entry.provider.lookup(&batch, fields)
405            })
406            .await;
407
408            let error = match answer {
409                Ok(resp) => {
410                    if let Some(u) = resp.usage {
411                        add_usage(usage, &provider, u);
412                    }
413                    // The contract is one answer per ID, in order; anything
414                    // else is a provider bug, not a miss.
415                    let in_order = resp.value.len() == batch.len()
416                        && resp.value.iter().zip(&batch).all(|(l, id)| &l.id == id);
417                    if in_order {
418                        let stored: Vec<_> = resp
419                            .value
420                            .iter()
421                            .map(|l| (&l.id, l.record.as_ref()))
422                            .collect();
423                        self.remember_lookups(&provider, &stored);
424                        for (&i, lookup) in chunk.iter().zip(resp.value) {
425                            let outcome = match lookup.record {
426                                Some(_) => Outcome::Found,
427                                None => Outcome::NotFound,
428                            };
429                            answers[i] = Some((attempt(outcome, Served::Live), lookup.record));
430                        }
431                        continue;
432                    }
433                    Error::decode(ContractViolation)
434                }
435                Err(error) => error,
436            };
437
438            // Out of budget or credentials: don't spend more calls on this
439            // provider in this lookup.
440            let give_up = matches!(
441                error.category(),
442                ErrorCategory::Throttled | ErrorCategory::Auth
443            );
444            let affected: Vec<usize> = if give_up {
445                chunk
446                    .iter()
447                    .chain(chunks.by_ref().flatten())
448                    .copied()
449                    .collect()
450            } else {
451                chunk.to_vec()
452            };
453            // Stale-on-error: an old answer beats none.
454            let affected_ids: Vec<WorkId> = affected.iter().map(|&i| ids[i].clone()).collect();
455            for (&i, stale) in affected
456                .iter()
457                .zip(self.stale_lookups(&provider, &affected_ids))
458            {
459                answers[i] = Some(match stale {
460                    Some(record) => (attempt(Outcome::Found, Served::Stale), Some(record)),
461                    None => (attempt(Outcome::Failed(error.clone()), Served::Live), None),
462                });
463            }
464        }
465        answers
466            .into_iter()
467            .map(|a| a.expect("every ID answered from cache, provider or failure"))
468            .collect()
469    }
470
471    /// Searches one provider: `source` if given, otherwise the first that
472    /// supports the query's mode.
473    pub async fn search(
474        &self,
475        source: Option<&str>,
476        query: &SearchQuery,
477    ) -> Result<SearchReport, EngineError> {
478        let citation = query.mode == SearchMode::Citation;
479        let entry = match source {
480            Some(name) => self
481                .entries
482                .iter()
483                .find(|e| e.provider.id().as_str() == name)
484                .ok_or_else(|| EngineError::UnknownProvider(name.to_owned()))?,
485            None => self
486                .entries
487                .iter()
488                .find(|e| {
489                    let caps = e.provider.capabilities();
490                    caps.search && (!citation || caps.citation_search)
491                })
492                .ok_or(EngineError::NoCapableProvider(if citation {
493                    "citation search"
494                } else {
495                    "search"
496                }))?,
497        };
498        let provider = entry.provider.id();
499        let caps = entry.provider.capabilities();
500        let refuse = |what| EngineError::Provider {
501            provider: provider.clone(),
502            error: Error::Unsupported(what),
503        };
504        if !caps.search {
505            return Err(refuse("search"));
506        }
507        if citation && !caps.citation_search {
508            return Err(refuse("citation search"));
509        }
510
511        let ignored_filters: Vec<Filter> = query
512            .filters()
513            .into_iter()
514            .filter(|f| !caps.search_filters.contains(f))
515            .collect();
516        let mut sent = query.clone();
517        for filter in &ignored_filters {
518            match filter {
519                Filter::Years => sent.years = None,
520                Filter::WorkType => sent.work_type = None,
521                Filter::OpenAccess => sent.open_access = None,
522                _ => {}
523            }
524        }
525
526        let report = |page, usage, served| SearchReport {
527            provider: provider.clone(),
528            page,
529            ignored_filters: ignored_filters.clone(),
530            usage,
531            served,
532        };
533        let cached = self.cached_search(&provider, &sent);
534        if let Some((page, true)) = cached {
535            tracing::info!(target: "aspero::cache", provider = %provider, text = %sent.text, "search served from cache");
536            return Ok(report(page, None, Served::Cache));
537        }
538        match with_retries(&entry.policy, self.jitter, || entry.provider.search(&sent)).await {
539            Ok(resp) => {
540                self.remember_search(&provider, &sent, &resp.value);
541                Ok(report(resp.value, resp.usage, Served::Live))
542            }
543            Err(error) => match cached {
544                Some((page, _)) => Ok(report(page, None, Served::Stale)),
545                None => Err(EngineError::Provider {
546                    provider: provider.clone(),
547                    error,
548                }),
549            },
550        }
551    }
552
553    // Cache access. Cache failures are never fatal: a broken cache behaves
554    // like an empty one, and failed writes are skipped.
555
556    /// For each ID, a fresh cached answer covering `fields`:
557    /// `Some(Some(record))`, `Some(None)` for a fresh "not found", or `None`
558    /// to ask the provider.
559    fn cached_lookups(
560        &self,
561        provider: &ProviderId,
562        ids: &[WorkId],
563        fields: FieldSet,
564    ) -> Vec<Option<Option<SourceRecord>>> {
565        let now = (self.clock)();
566        let policy = self.cache_policy;
567        self.cache_entries(provider, ids)
568            .into_iter()
569            .map(|entry| {
570                let entry = entry?;
571                match entry.value {
572                    Some(ref record)
573                        if entry.is_fresh(now, policy.records)
574                            && fields.is_subset(record.fields) =>
575                    {
576                        Some(entry.value)
577                    }
578                    None if entry.is_fresh(now, policy.misses) => Some(None),
579                    _ => None,
580                }
581            })
582            .collect()
583    }
584
585    /// For each ID, any cached record, however old.
586    fn stale_lookups(&self, provider: &ProviderId, ids: &[WorkId]) -> Vec<Option<SourceRecord>> {
587        self.cache_entries(provider, ids)
588            .into_iter()
589            .map(|entry| entry.and_then(|e| e.value))
590            .collect()
591    }
592
593    fn cache_entries(
594        &self,
595        provider: &ProviderId,
596        ids: &[WorkId],
597    ) -> Vec<Option<aspero_store::CachedLookup>> {
598        self.cache
599            .as_ref()
600            .and_then(|c| c.get_lookups(provider, ids).ok())
601            .unwrap_or_else(|| vec![None; ids.len()])
602    }
603
604    fn remember_lookups(
605        &self,
606        provider: &ProviderId,
607        answers: &[(&WorkId, Option<&SourceRecord>)],
608    ) {
609        if let Some(cache) = &self.cache {
610            let _ = cache.put_lookups(provider, answers, (self.clock)());
611        }
612    }
613
614    /// A cached page and whether it is still fresh.
615    fn cached_search(&self, provider: &ProviderId, query: &SearchQuery) -> Option<(Page, bool)> {
616        let entry = self.cache.as_ref()?.get_search(provider, query).ok()??;
617        let fresh = entry.is_fresh((self.clock)(), self.cache_policy.searches);
618        Some((entry.value, fresh))
619    }
620
621    fn remember_search(&self, provider: &ProviderId, query: &SearchQuery, page: &Page) {
622        if let Some(cache) = &self.cache {
623            let _ = cache.put_search(provider, query, page, (self.clock)());
624        }
625    }
626}
627
628fn add_usage(totals: &mut Vec<(ProviderId, Usage)>, provider: &ProviderId, usage: Usage) {
629    match totals.iter_mut().find(|(p, _)| p == provider) {
630        Some((_, total)) => *total = total.then(usage),
631        None => totals.push((provider.clone(), usage)),
632    }
633}
634
635#[derive(Debug, thiserror::Error)]
636#[error("provider answered a batch lookup out of order or incompletely")]
637struct ContractViolation;