qualia_core_db/domains/geospatial/adapters/
stac_adapter.rs1use crate::domains::geospatial::adapters::{AdapterHttpRequest, DataAdapter};
2use crate::net::disclosure::NetworkDisclosureRegistry;
3
4pub struct StacAdapter {
7 pub id: &'static str,
8 pub endpoint: String,
9 pub collection: Option<String>,
10}
11
12fn 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 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 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 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 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 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 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 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 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 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 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 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), ®istry);
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 assert_eq!(quins.len(), 7, "unexpected quin count: {}", quins.len());
234
235 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}