Skip to main content

qualia_core_db/domains/geospatial/adapters/
stac_adapter.rs

1use crate::domains::geospatial::adapters::{AdapterHttpRequest, DataAdapter};
2use crate::net::disclosure::NetworkDisclosureRegistry;
3
4/// Adapter for SpatioTemporal Asset Catalog (STAC) API endpoints.
5/// Supports querying JSON-based metadata via 4D bounding boxes (x, y, z, t).
6pub struct StacAdapter {
7    pub id: &'static str,
8    pub endpoint: String,
9    pub collection: Option<String>,
10}
11
12/// Build a provenance NQuin from three pre-hashed 60-bit tokens.
13/// Parity is the XOR fold of the three semantic vectors (matches the
14/// convention used elsewhere for lightweight integrity checks).
15fn quin(s: u64, p: u64, o: u64) -> crate::NQuin {
16    crate::NQuin {
17        subject: s,
18        predicate: p,
19        object: o,
20        context: 0,
21        metadata: 0,
22        parity: s ^ p ^ o,
23    }
24}
25
26impl StacAdapter {
27    /// Creates a default `StacAdapter`.
28    pub fn new(id: &'static str, endpoint: &str, collection: Option<&str>) -> Self {
29        Self {
30            id,
31            endpoint: endpoint.to_string(),
32            collection: collection.map(|s| s.to_string()),
33        }
34    }
35
36    /// Parse a STAC item-search response (a GeoJSON `FeatureCollection`) into
37    /// provenance `NQuin`s. IRIs are hashed with `generate_60bit_token` so the
38    /// resulting quins are queryable by the SPARQL layer, which hashes the same
39    /// way. Returns `Err` only when the body is not valid JSON; a response with
40    /// no `features` array yields an empty `Vec`.
41    pub fn parse_features(&self, body: &str) -> Result<Vec<crate::NQuin>, String> {
42        use crate::lexicon::generate_60bit_token;
43
44        let json: serde_json::Value = serde_json::from_str(body).map_err(|e| e.to_string())?;
45
46        // Predicate / kind hashes (stable, IRI-derived).
47        let title_p = generate_60bit_token(b"http://purl.org/dc/terms/title");
48        let type_p = generate_60bit_token(b"http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
49        let license_p = generate_60bit_token(b"http://purl.org/dc/terms/license");
50        let created_p = generate_60bit_token(b"http://purl.org/dc/terms/created");
51        let source_p = generate_60bit_token(b"http://purl.org/dc/terms/source");
52        let lat_p = generate_60bit_token(b"http://www.w3.org/2003/01/geo/wgs84_pos#lat");
53        let long_p = generate_60bit_token(b"http://www.w3.org/2003/01/geo/wgs84_pos#long");
54        let kind_o = generate_60bit_token(b"https://stacspec.org/Item");
55
56        let features = match json.get("features").and_then(|f| f.as_array()) {
57            Some(f) => f,
58            None => return Ok(Vec::new()),
59        };
60
61        let mut quins = Vec::new();
62        for (i, feature) in features.iter().enumerate() {
63            // Subject id: STAC feature "id", or a stable index fallback.
64            let id = feature
65                .get("id")
66                .and_then(|v| v.as_str())
67                .map(|s| s.to_string())
68                .unwrap_or_else(|| format!("stac:item:{}", i));
69            let subject = generate_60bit_token(id.as_bytes());
70
71            // Always: title (the item id) and rdf:type = STAC Item.
72            quins.push(quin(subject, title_p, generate_60bit_token(id.as_bytes())));
73            quins.push(quin(subject, type_p, kind_o));
74
75            let props = feature.get("properties");
76
77            // properties.datetime -> dc:created
78            if let Some(dt) = props
79                .and_then(|p| p.get("datetime"))
80                .and_then(|v| v.as_str())
81            {
82                quins.push(quin(
83                    subject,
84                    created_p,
85                    generate_60bit_token(dt.as_bytes()),
86                ));
87            }
88
89            // properties.license -> dc:license
90            if let Some(lic) = props
91                .and_then(|p| p.get("license"))
92                .and_then(|v| v.as_str())
93            {
94                quins.push(quin(
95                    subject,
96                    license_p,
97                    generate_60bit_token(lic.as_bytes()),
98                ));
99            }
100
101            // First asset href -> dc:source
102            if let Some(href) = feature
103                .get("assets")
104                .and_then(|a| a.as_object())
105                .and_then(|assets| assets.values().next())
106                .and_then(|asset| asset.get("href"))
107                .and_then(|v| v.as_str())
108            {
109                quins.push(quin(
110                    subject,
111                    source_p,
112                    generate_60bit_token(href.as_bytes()),
113                ));
114            }
115
116            // bbox (>=4 numbers) -> centre lat/long as raw f64 bits.
117            if let Some(bbox) = feature.get("bbox").and_then(|v| v.as_array()) {
118                if bbox.len() >= 4 {
119                    let coords: Option<Vec<f64>> =
120                        bbox.iter().take(4).map(|v| v.as_f64()).collect();
121                    if let Some(c) = coords {
122                        let long_c = (c[0] + c[2]) / 2.0;
123                        let lat_c = (c[1] + c[3]) / 2.0;
124                        quins.push(quin(subject, lat_p, lat_c.to_bits()));
125                        quins.push(quin(subject, long_p, long_c.to_bits()));
126                    }
127                }
128            }
129        }
130
131        Ok(quins)
132    }
133}
134
135impl DataAdapter for StacAdapter {
136    fn adapter_id(&self) -> &'static str {
137        self.id
138    }
139
140    fn build_fetch_request(
141        &self,
142        bbox: (f64, f64, f64, f64),
143        time_range: (u64, u64),
144        registry: &NetworkDisclosureRegistry,
145    ) -> Result<AdapterHttpRequest, String> {
146        if !registry.check_egress_consent(self.adapter_id(), &self.endpoint) {
147            return Err(format!(
148                "Consent denied or unregistered for STAC endpoint {}",
149                self.endpoint
150            ));
151        }
152
153        // Translate the bounding box and time_range into STAC API parameters
154        let stac_bbox = format!("{},{},{},{}", bbox.0, bbox.1, bbox.2, bbox.3);
155        let stac_datetime = if time_range.1 > 0 {
156            super::format_iso8601_range(time_range)
157        } else {
158            format!("{}/{}", time_range.0, time_range.1)
159        };
160
161        let mut url = format!(
162            "{}/search?bbox={}&datetime={}",
163            self.endpoint.trim_end_matches('/'),
164            stac_bbox,
165            stac_datetime
166        );
167        if let Some(c) = &self.collection {
168            url.push_str(&format!("&collections={}", c));
169        }
170
171        Ok(AdapterHttpRequest::get(url, "STAC"))
172    }
173
174    fn parse_response(&self, body: &str) -> Result<Vec<crate::NQuin>, String> {
175        self.parse_features(body)
176    }
177
178    fn primary_endpoint(&self) -> &str {
179        &self.endpoint
180    }
181
182    fn estimate_tile_count(&self, _bbox: (f64, f64, f64, f64)) -> u32 {
183        // STAC search is usually a single API query that returns multiple item records
184        1
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    #[test]
193    fn test_stac_adapter_consent_denied() {
194        let registry = NetworkDisclosureRegistry::new();
195        let adapter = StacAdapter::new(
196            "stac_adapter",
197            "https://planetarycomputer.microsoft.com/api/stac/v1",
198            Some("landsat-c2-l2"),
199        );
200
201        let res = adapter.fetch_region((0.0, 0.0, 1.0, 1.0), (0, 0), &registry);
202        assert!(res.is_err());
203    }
204
205    #[test]
206    fn test_stac_parse_features() {
207        use crate::lexicon::generate_60bit_token;
208
209        let body = r#"{
210            "type": "FeatureCollection",
211            "features": [
212                {
213                    "type": "Feature",
214                    "id": "S2A_31UFU_20230501",
215                    "bbox": [4.5, 51.0, 5.5, 52.0],
216                    "properties": {
217                        "datetime": "2023-05-01T10:00:00Z",
218                        "license": "proprietary",
219                        "platform": "sentinel-2a"
220                    },
221                    "assets": {
222                        "visual": {"href": "https://example/S2A.tif", "type": "image/tiff"}
223                    },
224                    "collection": "sentinel-2-l2a"
225                }
226            ]
227        }"#;
228
229        let adapter = StacAdapter::new("stac_adapter", "https://example/stac/v1", None);
230        let quins = adapter.parse_features(body).expect("valid STAC JSON");
231
232        // title + type + created + license + source + lat + long = 7 quins.
233        assert_eq!(quins.len(), 7, "unexpected quin count: {}", quins.len());
234
235        // The CREATED quin must be present with the exact expected hashes.
236        let subject = generate_60bit_token(b"S2A_31UFU_20230501");
237        let created_p = generate_60bit_token(b"http://purl.org/dc/terms/created");
238        let created_o = generate_60bit_token(b"2023-05-01T10:00:00Z");
239        assert!(
240            quins
241                .iter()
242                .any(|q| q.subject == subject && q.predicate == created_p && q.object == created_o),
243            "expected CREATED quin not found"
244        );
245    }
246}