Skip to main content

qualia_core_db/domains/geospatial/adapters/
opendap_adapter.rs

1use crate::domains::geospatial::adapters::{AdapterHttpRequest, DataAdapter};
2use crate::net::disclosure::NetworkDisclosureRegistry;
3
4/// Adapter for Open-source Project for a Network Data Access Protocol (OPeNDAP) endpoints.
5/// Primarily used for subsetting massive 4D/5D NetCDF arrays (e.g. atmospheric layers, ocean currents).
6pub struct OpendapAdapter {
7    pub id: &'static str,
8    pub endpoint: String,
9    pub dataset_id: String,
10}
11
12impl OpendapAdapter {
13    /// Creates a default `OpendapAdapter`.
14    pub fn new(id: &'static str, endpoint: &str, dataset_id: &str) -> Self {
15        Self {
16            id,
17            endpoint: endpoint.to_string(),
18            dataset_id: dataset_id.to_string(),
19        }
20    }
21}
22
23impl DataAdapter for OpendapAdapter {
24    fn adapter_id(&self) -> &'static str {
25        self.id
26    }
27
28    fn build_fetch_request(
29        &self,
30        _bbox: (f64, f64, f64, f64),
31        _time_range: (u64, u64),
32        registry: &NetworkDisclosureRegistry,
33    ) -> Result<AdapterHttpRequest, String> {
34        if !registry.check_egress_consent(self.adapter_id(), &self.endpoint) {
35            return Err(format!(
36                "Consent denied or unregistered for OPeNDAP endpoint {}",
37                self.endpoint
38            ));
39        }
40
41        // Construct OPeNDAP constraint expression assuming standard lat/lon mapping for a spatial subset.
42        // Example: ?variable[lat_idx_min:1:lat_idx_max][lon_idx_min:1:lon_idx_max]
43        // Since we don't have the DDS to resolve indices here, we fetch the DDS endpoint to verify access.
44        let dds_url = format!("{}.dds", self.endpoint);
45
46        Ok(AdapterHttpRequest::get(dds_url, "OPeNDAP"))
47    }
48
49    fn primary_endpoint(&self) -> &str {
50        &self.endpoint
51    }
52
53    fn estimate_tile_count(&self, _bbox: (f64, f64, f64, f64)) -> u32 {
54        // Typically a DDS fetch followed by a targeted subset request
55        2
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn test_opendap_adapter_consent_denied() {
65        let registry = NetworkDisclosureRegistry::new();
66        let adapter = OpendapAdapter::new(
67            "opendap_adapter",
68            "https://cds.climate.copernicus.eu/api",
69            "era5",
70        );
71
72        let res = adapter.fetch_region((0.0, 0.0, 1.0, 1.0), (0, 0), &registry);
73        assert!(res.is_err());
74    }
75}