Skip to main content

superstac_engine/
engine.rs

1use parking_lot::Mutex;
2use reqwest::Client;
3use std::sync::{
4    atomic::{AtomicBool, Ordering},
5    Arc,
6};
7
8use std::collections::{HashMap, HashSet};
9
10use crate::{
11    capabilities,
12    discovery::{self, CollectionAvailability},
13    health::HealthManager,
14    types::SharedStorage,
15};
16use std::time::Duration;
17use superstac_core::{
18    errors::SuperSTACError,
19    models::catalog::{Catalog, CatalogFilters},
20    storages::factory::StorageBackend,
21};
22
23use superstac_search::{
24    executor::SearchExecutor,
25    // TODO - Move this to settings.
26    options::{FederationOptions, RetryPolicy},
27    query::SearchQuery,
28    response::SearchResponse,
29};
30
31/// Runtime entry point. Wraps a storage backend, runs background health
32/// checks and `/collections` introspection, and exposes the federated search
33/// + discovery API.
34///
35/// Construct, call `start()`, then use `search()` / `list_collections()` /
36/// `describe_collection()`. `start()` is idempotent — `search()` will call
37/// it for you if needed.
38pub struct SuperSTACEngine {
39    storage: SharedStorage,
40    client: Client,
41    health_manager: Option<HealthManager>,
42    executor: SearchExecutor,
43    snapshot_catalog_ids: Option<HashSet<String>>,
44    auto_search: bool,
45    #[cfg(feature = "geoparquet")]
46    local_backend: Option<Arc<superstac_geoparquet::GeoParquetBackend>>,
47    pub started: AtomicBool,
48}
49
50/// User-Agent attached to every outbound HTTP request. Set as a default
51/// header on the shared reqwest client at engine construction. When
52/// per-catalog headers are added later, this must be filtered out of any
53/// user-supplied set so it can't be overridden.
54const USER_AGENT: &'static str = concat!("superstac/", env!("CARGO_PKG_VERSION"));
55
56impl SuperSTACEngine {
57    /// Build an engine over the given storage. Construct the storage via
58    /// `superstac_config::init_from_yaml` or directly via
59    /// [`superstac_core::models::storage::Storage::init`].
60    pub fn new(storage: Box<dyn StorageBackend + Send + Sync>) -> Self {
61        Self::from_shared(Arc::new(Mutex::new(storage)))
62    }
63
64    /// Build an engine over an already-shared storage handle. Useful when a
65    /// caller (e.g. the Python bindings) needs to retain mutation access to
66    /// the same backend the engine reads from.
67    pub fn from_shared(storage: SharedStorage) -> Self {
68        let client = Client::builder()
69            .user_agent(USER_AGENT)
70            .build()
71            .expect("failed to build reqwest client");
72
73        Self {
74            storage,
75            client: client.clone(),
76            health_manager: Some(HealthManager::new(client.clone())),
77            executor: SearchExecutor::new(client),
78            snapshot_catalog_ids: None,
79            auto_search: false,
80            #[cfg(feature = "geoparquet")]
81            local_backend: None,
82            started: AtomicBool::new(false),
83        }
84    }
85
86    /// Search only the supplied local snapshots. IDs must already exist in storage.
87    /// Provider health, API introspection, and cached remote collection inventories
88    /// are ignored. Collection discovery is not yet available in snapshot mode.
89    #[cfg(feature = "geoparquet")]
90    pub fn from_geoparquet(
91        storage: Box<dyn StorageBackend + Send + Sync>,
92        paths: HashMap<String, std::path::PathBuf>,
93    ) -> Result<Self, SuperSTACError> {
94        Self::from_shared_geoparquet(Arc::new(Mutex::new(storage)), paths)
95    }
96
97    #[cfg(feature = "geoparquet")]
98    pub fn from_shared_geoparquet(
99        storage: SharedStorage,
100        paths: HashMap<String, std::path::PathBuf>,
101    ) -> Result<Self, SuperSTACError> {
102        for id in paths.keys() {
103            storage.lock().get_catalog(id)?;
104        }
105        let ids = paths.keys().cloned().collect();
106        let backend = superstac_geoparquet::GeoParquetBackend::new(paths)?;
107        let mut engine = Self::from_shared(storage);
108        let backend = Arc::new(backend);
109        engine.executor = SearchExecutor::with_backend(Box::new(backend.clone()));
110        engine.local_backend = Some(backend);
111        engine.health_manager = None;
112        engine.snapshot_catalog_ids = Some(ids);
113        Ok(engine)
114    }
115
116    /// Open completed catalog snapshots from a managed dataset. Search coverage
117    /// is checked against the manifest; no provider checks or requests occur.
118    #[cfg(feature = "geoparquet")]
119    pub fn from_dataset(
120        storage: Box<dyn StorageBackend + Send + Sync>,
121        root: impl AsRef<std::path::Path>,
122    ) -> Result<Self, SuperSTACError> {
123        Self::from_shared_dataset(Arc::new(Mutex::new(storage)), root)
124    }
125
126    #[cfg(feature = "geoparquet")]
127    pub fn from_shared_dataset(
128        storage: SharedStorage,
129        root: impl AsRef<std::path::Path>,
130    ) -> Result<Self, SuperSTACError> {
131        let backend = superstac_geoparquet::GeoParquetBackend::from_dataset(root)?;
132        for id in backend.catalog_ids() {
133            storage.lock().get_catalog(id)?;
134        }
135        let ids = backend.catalog_ids().cloned().collect();
136        let mut engine = Self::from_shared(storage);
137        let backend = Arc::new(backend);
138        engine.executor = SearchExecutor::with_backend(Box::new(backend.clone()));
139        engine.local_backend = Some(backend);
140        engine.health_manager = None;
141        engine.snapshot_catalog_ids = Some(ids);
142        Ok(engine)
143    }
144
145    /// Prefer one fresh covering snapshot per catalog, otherwise query its API.
146    /// This mode never writes datasets and skips provider monitoring/introspection.
147    #[cfg(feature = "geoparquet")]
148    pub fn automatic(
149        storage: Box<dyn StorageBackend + Send + Sync>,
150        root: impl Into<std::path::PathBuf>,
151        max_snapshot_age: Duration,
152    ) -> Self {
153        Self::from_shared_automatic(Arc::new(Mutex::new(storage)), root, max_snapshot_age)
154    }
155
156    #[cfg(feature = "geoparquet")]
157    pub fn from_shared_automatic(
158        storage: SharedStorage,
159        root: impl Into<std::path::PathBuf>,
160        max_snapshot_age: Duration,
161    ) -> Self {
162        let mut engine = Self::from_shared(storage);
163        let backend = superstac_geoparquet::auto::AutoBackend::new(
164            root.into(),
165            max_snapshot_age,
166            engine.client.clone(),
167        );
168        engine.executor = SearchExecutor::with_backend(Box::new(backend));
169        engine.health_manager = None;
170        engine.auto_search = true;
171        engine
172    }
173
174    async fn discovery_catalogs(&self) -> Result<Vec<Catalog>, SuperSTACError> {
175        self.ensure_started().await?;
176        let mut catalogs = self.storage.lock().list_catalogs(None)?;
177        #[cfg(feature = "geoparquet")]
178        if let Some(backend) = &self.local_backend {
179            catalogs.retain(|c| {
180                self.snapshot_catalog_ids
181                    .as_ref()
182                    .is_some_and(|ids| ids.contains(&c.id))
183            });
184            for catalog in &mut catalogs {
185                let backend = backend.clone();
186                let copy = catalog.clone();
187                let collections = tokio::task::spawn_blocking(move || backend.collections(&copy))
188                    .await
189                    .map_err(|e| SuperSTACError::SearchFailed(e.to_string()))??;
190                catalog.supported_collections = Some(collections.into_keys().collect());
191            }
192        }
193        if self.auto_search {
194            for catalog in &mut catalogs {
195                catalog.supported_collections =
196                    Some(capabilities::fetch_supported_collections(&self.client, catalog).await?);
197            }
198        }
199        Ok(catalogs)
200    }
201
202    /// Run health checks against all catalogs, then introspect `/collections`
203    /// on the healthy ones. Snapshot mode skips all provider access.
204    /// Idempotent — safe to call multiple times.
205    pub async fn start(&self) -> Result<(), SuperSTACError> {
206        if self.started.load(Ordering::Relaxed) {
207            return Ok(());
208        }
209
210        if self.snapshot_catalog_ids.is_some() || self.auto_search {
211            self.started.store(true, Ordering::Relaxed);
212            return Ok(());
213        }
214
215        if let Some(manager) = &self.health_manager {
216            let catalogs = {
217                let storage = self.storage.lock();
218                storage.list_catalogs(None)?
219            };
220
221            manager.start(Arc::clone(&self.storage), catalogs).await?;
222        }
223
224        // Introspect each healthy catalog's /collections so we can do source
225        // selection at search time. Failures here are non-fatal — affected
226        // catalogs remain `supported_collections = None` (pass-through).
227        // TODO - Maybe have a way to disable this by default ?
228        self.introspect_capabilities().await?;
229
230        self.started.store(true, Ordering::Relaxed);
231
232        let catalog_count = self.storage.lock().list_catalogs(None)?.len();
233        tracing::info!(catalogs = catalog_count, "engine ready");
234
235        Ok(())
236    }
237
238    /// Cancel background health-monitor tasks. Doesn't drop the storage.
239    pub async fn shutdown(&self) {
240        tracing::debug!("shutting down engine");
241
242        if let Some(manager) = &self.health_manager {
243            manager.stop_all().await;
244        }
245
246        self.started.store(false, Ordering::Relaxed);
247    }
248
249    /// Run health checks against every catalog, update storage with results. Then update the `supported_collections` sets for any newly-healthy catalogs.
250    async fn introspect_capabilities(&self) -> Result<(), SuperSTACError> {
251        let healthy_catalogs = {
252            let storage = self.storage.lock();
253            storage.list_catalogs(Some(CatalogFilters {
254                available: Some(true),
255                ..CatalogFilters::default()
256            }))?
257        };
258
259        for catalog in healthy_catalogs {
260            match capabilities::fetch_supported_collections(&self.client, &catalog).await {
261                Ok(set) => {
262                    tracing::debug!(
263                        catalog = %catalog.id,
264                        collections = set.len(),
265                        "introspected /collections"
266                    );
267                    let mut storage = self.storage.lock();
268                    if let Err(e) = storage.update_supported_collections(&catalog.id, Some(set)) {
269                        tracing::warn!(
270                            catalog = %catalog.id,
271                            error = %e,
272                            "failed to persist /collections result"
273                        );
274                    }
275                }
276                Err(e) => {
277                    tracing::warn!(
278                        catalog = %catalog.id,
279                        error = %e,
280                        "/collections introspection failed; catalog will pass-through"
281                    );
282                }
283            }
284        }
285
286        Ok(())
287    }
288
289    /// `start()` if we haven't already. Called automatically by `search()`
290    /// and the discovery methods.
291    pub async fn ensure_started(&self) -> Result<(), SuperSTACError> {
292        if !self.started.load(Ordering::Relaxed) {
293            self.start().await?;
294        }
295
296        Ok(())
297    }
298
299    /// Federated search. Applies source selection (filter catalogs that
300    /// can't possibly serve the requested collections), then fans out.
301    pub async fn search(&self, query: SearchQuery) -> Result<SearchResponse, SuperSTACError> {
302        self.ensure_started().await?;
303
304        let (candidate_catalogs, options) = {
305            let storage = self.storage.lock();
306            let settings = storage.get_settings();
307
308            let catalogs = if let Some(ids) = &self.snapshot_catalog_ids {
309                let mut catalogs = Vec::new();
310                for id in ids {
311                    let mut catalog = storage.get_catalog(id)?.clone();
312                    // A remote inventory may be stale or differ from the snapshot.
313                    catalog.supported_collections = None;
314                    catalogs.push(catalog);
315                }
316                catalogs
317            } else if self.auto_search {
318                let mut catalogs = storage.list_catalogs(None)?;
319                for catalog in &mut catalogs {
320                    catalog.supported_collections = None;
321                }
322                catalogs
323            } else if let Some(true) = settings.search_healthy_catalogs_only {
324                storage.list_catalogs(Some(CatalogFilters {
325                    available: Some(true),
326                    ..CatalogFilters::default()
327                }))?
328            } else {
329                storage.list_catalogs(None)?
330            };
331
332            let options = FederationOptions {
333                deduplicate: settings.deduplicate_items.unwrap_or(true),
334                unify_response: settings.unify_response.unwrap_or(true),
335                max_concurrent: settings.max_concurrent_catalogs.unwrap_or(8),
336                per_catalog_timeout: Duration::from_secs(
337                    settings.per_catalog_timeout_seconds.unwrap_or(30),
338                ),
339                retry: RetryPolicy {
340                    max_attempts: if self.snapshot_catalog_ids.is_some() {
341                        1
342                    } else {
343                        settings.max_retry_attempts.unwrap_or(2)
344                    },
345                    initial_backoff: Duration::from_millis(
346                        settings.retry_initial_backoff_ms.unwrap_or(100),
347                    ),
348                    max_backoff: Duration::from_millis(
349                        settings.retry_max_backoff_ms.unwrap_or(2000),
350                    ),
351                },
352                max_items_per_catalog: settings.max_items_per_catalog.unwrap_or(1000),
353            };
354
355            (catalogs, options)
356        };
357
358        // Compute unsupported collections against the full candidate set
359        // before source-selection filtering.
360        let unsupported =
361            discovery::unsupported_collections(&candidate_catalogs, &query.collections);
362
363        // Source selection: drop catalogs whose introspected collection set
364        // doesn't overlap the requested collections. Catalogs with no
365        // introspection data pass through.
366        let catalogs: Vec<Catalog> = candidate_catalogs
367            .into_iter()
368            .filter(|c| c.supports_any_of(&query.collections))
369            .collect();
370
371        // Perform the federated search across the selected catalogs.
372        let mut response = self
373            .executor
374            .federated_search(catalogs, query, options)
375            .await?;
376
377        response.metadata.unsupported_collections = unsupported;
378
379        Ok(response)
380    }
381
382    /// Aggregated view: every collection ID known across healthy catalogs,
383    /// with the catalogs that serve each.
384    pub async fn list_collections(&self) -> Result<Vec<CollectionAvailability>, SuperSTACError> {
385        let catalogs = self.discovery_catalogs().await?;
386        Ok(discovery::aggregate_collections(&catalogs))
387    }
388
389    /// IDs of every catalog whose introspected `/collections` includes
390    /// `collection_id`. Catalogs not yet introspected are excluded.
391    pub async fn catalogs_supporting(
392        &self,
393        collection_id: &str,
394    ) -> Result<Vec<String>, SuperSTACError> {
395        let catalogs = self.discovery_catalogs().await?;
396        Ok(discovery::catalogs_supporting(&catalogs, collection_id))
397    }
398
399    /// Per-catalog inventory: catalog ID -> sorted canonical collection IDs.
400    /// Catalogs without introspection data are omitted.
401    pub async fn collections_by_catalog(
402        &self,
403    ) -> Result<HashMap<String, Vec<String>>, SuperSTACError> {
404        let catalogs = self.discovery_catalogs().await?;
405        Ok(discovery::collections_by_catalog(&catalogs))
406    }
407
408    /// Fetch full collection metadata from a specific catalog. The
409    /// `collection_id` is interpreted as canonical and resolved to the
410    /// catalog's local name via `collection_aliases`. Returns `None` if the
411    /// catalog returns 404 for the collection.
412    pub async fn describe_collection(
413        &self,
414        catalog_id: &str,
415        collection_id: &str,
416    ) -> Result<Option<stac::Collection>, SuperSTACError> {
417        self.ensure_started().await?;
418
419        let catalog = {
420            let storage = self.storage.lock();
421            storage.get_catalog(catalog_id)?.clone()
422        };
423
424        #[cfg(feature = "geoparquet")]
425        if let Some(backend) = &self.local_backend {
426            let backend = backend.clone();
427            let id = collection_id.to_owned();
428            return tokio::task::spawn_blocking(move || {
429                backend.collections(&catalog).map(|mut c| c.remove(&id))
430            })
431            .await
432            .map_err(|e| SuperSTACError::SearchFailed(e.to_string()))?;
433        }
434
435        let local_id = catalog.resolve_collection(collection_id).to_string();
436
437        let stac_client = stac_io::api::Client::with_client(self.client.clone(), &catalog.url)
438            .map_err(|e| SuperSTACError::SearchFailed(format!("stac client init: {}", e)))?;
439
440        stac_client
441            .collection(&local_id)
442            .await
443            .map_err(|e| SuperSTACError::SearchFailed(format!("fetch collection: {}", e)))
444    }
445}