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;
9
10use crate::{
11    capabilities,
12    discovery::{self, CollectionAvailability},
13    health::HealthManager,
14    types::SharedStorage,
15};
16use superstac_core::{
17    errors::SuperSTACError,
18    models::catalog::{Catalog, CatalogFilters},
19    storages::factory::StorageBackend,
20};
21use std::time::Duration;
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    pub started: AtomicBool,
44}
45
46/// User-Agent attached to every outbound HTTP request. Set as a default
47/// header on the shared reqwest client at engine construction. When
48/// per-catalog headers are added later, this must be filtered out of any
49/// user-supplied set so it can't be overridden.
50const USER_AGENT: &'static str = concat!("superstac/", env!("CARGO_PKG_VERSION"));
51
52impl SuperSTACEngine {
53    /// Build an engine over the given storage. Construct the storage via
54    /// `superstac_config::init_from_yaml` or directly via
55    /// [`superstac_core::models::storage::Storage::init`].
56    pub fn new(storage: Box<dyn StorageBackend + Send + Sync>) -> Self {
57        Self::from_shared(Arc::new(Mutex::new(storage)))
58    }
59
60    /// Build an engine over an already-shared storage handle. Useful when a
61    /// caller (e.g. the Python bindings) needs to retain mutation access to
62    /// the same backend the engine reads from.
63    pub fn from_shared(storage: SharedStorage) -> Self {
64        let client = Client::builder()
65            .user_agent(USER_AGENT)
66            .build()
67            .expect("failed to build reqwest client");
68
69        Self {
70            storage,
71            client: client.clone(),
72            health_manager: Some(HealthManager::new(client.clone())),
73            executor: SearchExecutor::new(client),
74            started: AtomicBool::new(false),
75        }
76    }
77
78    /// Run health checks against all catalogs, then introspect `/collections`
79    /// on the healthy ones. Idempotent — safe to call multiple times.
80    pub async fn start(&self) -> Result<(), SuperSTACError> {
81        if self.started.load(Ordering::Relaxed) {
82            return Ok(());
83        }
84
85        if let Some(manager) = &self.health_manager {
86            let catalogs = {
87                let storage = self.storage.lock();
88                storage.list_catalogs(None)?
89            };
90
91            manager.start(Arc::clone(&self.storage), catalogs).await?;
92        }
93
94        // Introspect each healthy catalog's /collections so we can do source
95        // selection at search time. Failures here are non-fatal — affected
96        // catalogs remain `supported_collections = None` (pass-through).
97        // TODO - Maybe have a way to disable this by default ?
98        self.introspect_capabilities().await?;
99
100        self.started.store(true, Ordering::Relaxed);
101
102        let catalog_count = self.storage.lock().list_catalogs(None)?.len();
103        tracing::info!(catalogs = catalog_count, "engine ready");
104
105        Ok(())
106    }
107
108    /// Cancel background health-monitor tasks. Doesn't drop the storage.
109    pub async fn shutdown(&self) {
110        tracing::debug!("shutting down engine");
111
112        if let Some(manager) = &self.health_manager {
113            manager.stop_all().await;
114        }
115
116        self.started.store(false, Ordering::Relaxed);
117    }
118
119    /// Run health checks against every catalog, update storage with results. Then update the `supported_collections` sets for any newly-healthy catalogs. 
120    async fn introspect_capabilities(&self) -> Result<(), SuperSTACError> {
121        let healthy_catalogs = {
122            let storage = self.storage.lock();
123            storage.list_catalogs(Some(CatalogFilters {
124                available: Some(true),
125                ..CatalogFilters::default()
126            }))?
127        };
128
129        for catalog in healthy_catalogs {
130            match capabilities::fetch_supported_collections(&self.client, &catalog).await {
131                Ok(set) => {
132                    tracing::debug!(
133                        catalog = %catalog.id,
134                        collections = set.len(),
135                        "introspected /collections"
136                    );
137                    let mut storage = self.storage.lock();
138                    if let Err(e) =
139                        storage.update_supported_collections(&catalog.id, Some(set))
140                    {
141                        tracing::warn!(
142                            catalog = %catalog.id,
143                            error = %e,
144                            "failed to persist /collections result"
145                        );
146                    }
147                }
148                Err(e) => {
149                    tracing::warn!(
150                        catalog = %catalog.id,
151                        error = %e,
152                        "/collections introspection failed; catalog will pass-through"
153                    );
154                }
155            }
156        }
157
158        Ok(())
159    }
160
161    /// `start()` if we haven't already. Called automatically by `search()`
162    /// and the discovery methods.
163    pub async fn ensure_started(&self) -> Result<(), SuperSTACError> {
164        if !self.started.load(Ordering::Relaxed) {
165            self.start().await?;
166        }
167
168        Ok(())
169    }
170
171    /// Federated search. Applies source selection (filter catalogs that
172    /// can't possibly serve the requested collections), then fans out.
173    pub async fn search(&self, query: SearchQuery) -> Result<SearchResponse, SuperSTACError> {
174        
175        self.ensure_started().await?;
176
177        let (candidate_catalogs, options) = {
178            let storage = self.storage.lock();
179            let settings = storage.get_settings();
180
181            let catalogs = if let Some(true) = settings.search_healthy_catalogs_only {
182                storage.list_catalogs(Some(CatalogFilters {
183                    available: Some(true),
184                    ..CatalogFilters::default()
185                }))?
186            } else {
187                storage.list_catalogs(None)?
188            };
189
190            let options = FederationOptions {
191                deduplicate: settings.deduplicate_items.unwrap_or(true),
192                unify_response: settings.unify_response.unwrap_or(true),
193                max_concurrent: settings.max_concurrent_catalogs.unwrap_or(8),
194                per_catalog_timeout: Duration::from_secs(
195                    settings.per_catalog_timeout_seconds.unwrap_or(30),
196                ),
197                retry: RetryPolicy {
198                    max_attempts: settings.max_retry_attempts.unwrap_or(2),
199                    initial_backoff: Duration::from_millis(
200                        settings.retry_initial_backoff_ms.unwrap_or(100),
201                    ),
202                    max_backoff: Duration::from_millis(
203                        settings.retry_max_backoff_ms.unwrap_or(2000),
204                    ),
205                },
206                max_items_per_catalog: settings.max_items_per_catalog.unwrap_or(1000),
207            };
208
209            (catalogs, options)
210        };
211
212        // Compute unsupported collections against the full candidate set
213        // before source-selection filtering.
214        let unsupported =
215            discovery::unsupported_collections(&candidate_catalogs, &query.collections);
216
217        // Source selection: drop catalogs whose introspected collection set
218        // doesn't overlap the requested collections. Catalogs with no
219        // introspection data pass through.
220        let catalogs: Vec<Catalog> = candidate_catalogs
221            .into_iter()
222            .filter(|c| c.supports_any_of(&query.collections))
223            .collect();
224        
225
226        // Perform the federated search across the selected catalogs.
227        let mut response = self
228            .executor
229            .federated_search(catalogs, query, options)
230            .await?;
231        
232        response.metadata.unsupported_collections = unsupported;
233
234        Ok(response)
235    }
236
237    /// Aggregated view: every collection ID known across healthy catalogs,
238    /// with the catalogs that serve each.
239    pub async fn list_collections(&self) -> Result<Vec<CollectionAvailability>, SuperSTACError> {
240        self.ensure_started().await?;
241        let catalogs = {
242            let storage = self.storage.lock();
243            storage.list_catalogs(None)?
244        };
245        Ok(discovery::aggregate_collections(&catalogs))
246    }
247
248    /// IDs of every catalog whose introspected `/collections` includes
249    /// `collection_id`. Catalogs not yet introspected are excluded.
250    pub async fn catalogs_supporting(
251        &self,
252        collection_id: &str,
253    ) -> Result<Vec<String>, SuperSTACError> {
254        self.ensure_started().await?;
255        let catalogs = {
256            let storage = self.storage.lock();
257            storage.list_catalogs(None)?
258        };
259        Ok(discovery::catalogs_supporting(&catalogs, collection_id))
260    }
261
262    /// Per-catalog inventory: catalog ID -> sorted canonical collection IDs.
263    /// Catalogs without introspection data are omitted.
264    pub async fn collections_by_catalog(
265        &self,
266    ) -> Result<HashMap<String, Vec<String>>, SuperSTACError> {
267        self.ensure_started().await?;
268        let catalogs = {
269            let storage = self.storage.lock();
270            storage.list_catalogs(None)?
271        };
272        Ok(discovery::collections_by_catalog(&catalogs))
273    }
274
275    /// Fetch full collection metadata from a specific catalog. The
276    /// `collection_id` is interpreted as canonical and resolved to the
277    /// catalog's local name via `collection_aliases`. Returns `None` if the
278    /// catalog returns 404 for the collection.
279    pub async fn describe_collection(
280        &self,
281        catalog_id: &str,
282        collection_id: &str,
283    ) -> Result<Option<stac::Collection>, SuperSTACError> {
284        self.ensure_started().await?;
285
286        let catalog = {
287            let storage = self.storage.lock();
288            storage.get_catalog(catalog_id)?.clone()
289        };
290
291        let local_id = catalog.resolve_collection(collection_id).to_string();
292
293        let stac_client =
294            stac_io::api::Client::with_client(self.client.clone(), &catalog.url)
295                .map_err(|e| SuperSTACError::SearchFailed(format!("stac client init: {}", e)))?;
296
297        stac_client
298            .collection(&local_id)
299            .await
300            .map_err(|e| SuperSTACError::SearchFailed(format!("fetch collection: {}", e)))
301    }
302}