1pub mod astrometry_adapter;
4pub mod ckan_adapter;
5pub mod dem_adapter;
6pub mod gbif_adapter;
7pub mod ivoa_tap_adapter;
8pub mod ogc_3d_tiles;
9pub mod opendap_adapter;
10pub mod osm_adapter;
11pub mod sparql_adapter;
12pub mod stac_adapter;
13pub mod wms_adapter;
14
15pub mod canvas_defaults;
16
17use std::collections::HashMap;
18
19use crate::net::disclosure::NetworkDisclosureRegistry;
20
21pub use astrometry_adapter::AstrometryAdapter;
22pub use ckan_adapter::CkanAdapter;
23pub use dem_adapter::{DemAdapter, DemHeightfield, DemTerrainAsset};
24pub use gbif_adapter::GbifAdapter;
25pub use ivoa_tap_adapter::IvoaTapAdapter;
26pub use ogc_3d_tiles::Ogc3dTilesAdapter;
27pub use opendap_adapter::OpendapAdapter;
28pub use osm_adapter::OsmAdapter;
29pub use sparql_adapter::SparqlAdapter;
30pub use stac_adapter::StacAdapter;
31pub use wms_adapter::WmsAdapter;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum AdapterHttpMethod {
35 Get,
36 Post,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct AdapterHttpRequest {
41 pub method: AdapterHttpMethod,
42 pub url: String,
43 pub body: Option<String>,
44 pub content_type: Option<&'static str>,
45 pub service_label: &'static str,
46}
47
48impl AdapterHttpRequest {
49 pub fn get(url: String, service_label: &'static str) -> Self {
52 Self {
53 method: AdapterHttpMethod::Get,
54 url,
55 body: None,
56 content_type: None,
57 service_label,
58 }
59 }
60
61 pub fn post_form(url: String, body: String, service_label: &'static str) -> Self {
64 Self {
65 method: AdapterHttpMethod::Post,
66 url,
67 body: Some(body),
68 content_type: Some("application/x-www-form-urlencoded"),
69 service_label,
70 }
71 }
72}
73
74pub fn format_iso8601_range(time_range: (u64, u64)) -> String {
76 let fmt_single = |ts: u64| -> String {
77 let ms = if ts < 10_000_000_000 { ts * 1000 } else { ts };
78 chrono::DateTime::from_timestamp_millis(ms as i64)
79 .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
80 .unwrap_or_else(|| format!("{ts}"))
81 };
82 format!("{}/{}", fmt_single(time_range.0), fmt_single(time_range.1))
83}
84
85#[cfg(not(target_arch = "wasm32"))]
88fn execute_http_request_text(request: &AdapterHttpRequest) -> Result<String, String> {
89 let _ = rustls::crypto::ring::default_provider().install_default();
90 let client = reqwest::blocking::Client::new();
91 let mut builder = match request.method {
92 AdapterHttpMethod::Get => client.get(&request.url),
93 AdapterHttpMethod::Post => client.post(&request.url),
94 };
95 if let Some(content_type) = request.content_type {
96 builder = builder.header("Content-Type", content_type);
97 }
98 if let Some(body) = &request.body {
99 builder = builder.body(body.clone());
100 }
101
102 let resp = builder.send().map_err(|e| e.to_string())?;
103 if !resp.status().is_success() {
104 return Err(format!(
105 "{} API returned error: {}",
106 request.service_label,
107 resp.status()
108 ));
109 }
110 resp.text().map_err(|e| e.to_string())
111}
112
113#[cfg(not(target_arch = "wasm32"))]
116fn execute_http_request_bytes(request: &AdapterHttpRequest) -> Result<Vec<u8>, String> {
117 let _ = rustls::crypto::ring::default_provider().install_default();
118 let client = reqwest::blocking::Client::new();
119 let mut builder = match request.method {
120 AdapterHttpMethod::Get => client.get(&request.url),
121 AdapterHttpMethod::Post => client.post(&request.url),
122 };
123 if let Some(content_type) = request.content_type {
124 builder = builder.header("Content-Type", content_type);
125 }
126 if let Some(body) = &request.body {
127 builder = builder.body(body.clone());
128 }
129 let response = builder.send().map_err(|error| error.to_string())?;
130 if !response.status().is_success() {
131 return Err(format!(
132 "{} API returned error: {}",
133 request.service_label,
134 response.status()
135 ));
136 }
137 response
138 .bytes()
139 .map(|bytes| bytes.to_vec())
140 .map_err(|error| error.to_string())
141}
142
143#[cfg(not(target_arch = "wasm32"))]
146fn execute_http_request_status(request: &AdapterHttpRequest) -> Result<(), String> {
147 execute_http_request_text(request).map(|_| ())
148}
149
150#[cfg(target_arch = "wasm32")]
153async fn execute_http_request_text_async(request: &AdapterHttpRequest) -> Result<String, String> {
154 let client = reqwest::Client::new();
155 let mut builder = match request.method {
156 AdapterHttpMethod::Get => client.get(&request.url),
157 AdapterHttpMethod::Post => client.post(&request.url),
158 };
159 if let Some(content_type) = request.content_type {
160 builder = builder.header("Content-Type", content_type);
161 }
162 if let Some(body) = &request.body {
163 builder = builder.body(body.clone());
164 }
165
166 let resp = builder.send().await.map_err(|e| e.to_string())?;
167 let status = resp.status();
168 if !status.is_success() {
169 return Err(format!(
170 "{} API returned error: {status}",
171 request.service_label
172 ));
173 }
174 resp.text().await.map_err(|e| e.to_string())
175}
176
177#[cfg(target_arch = "wasm32")]
179async fn execute_http_request_bytes_async(request: &AdapterHttpRequest) -> Result<Vec<u8>, String> {
180 let client = reqwest::Client::new();
181 let mut builder = match request.method {
182 AdapterHttpMethod::Get => client.get(&request.url),
183 AdapterHttpMethod::Post => client.post(&request.url),
184 };
185 if let Some(content_type) = request.content_type {
186 builder = builder.header("Content-Type", content_type);
187 }
188 if let Some(body) = &request.body {
189 builder = builder.body(body.clone());
190 }
191 let response = builder.send().await.map_err(|error| error.to_string())?;
192 if !response.status().is_success() {
193 return Err(format!(
194 "{} API returned error: {}",
195 request.service_label,
196 response.status()
197 ));
198 }
199 response
200 .bytes()
201 .await
202 .map(|bytes| bytes.to_vec())
203 .map_err(|error| error.to_string())
204}
205
206#[cfg(target_arch = "wasm32")]
209fn execute_http_request_status(_request: &AdapterHttpRequest) -> Result<(), String> {
210 Err(
211 "Synchronous geospatial HTTP is unavailable on wasm32; call fetch_region_async instead"
212 .to_string(),
213 )
214}
215
216#[cfg(target_arch = "wasm32")]
219fn execute_http_request_text(_request: &AdapterHttpRequest) -> Result<String, String> {
220 Err(
221 "Synchronous geospatial HTTP is unavailable on wasm32; call fetch_region_async instead"
222 .to_string(),
223 )
224}
225
226#[cfg(target_arch = "wasm32")]
230pub async fn fetch_region_async(
231 adapter: &dyn DataAdapter,
232 bbox: (f64, f64, f64, f64),
233 time_range: (u64, u64),
234 registry: &NetworkDisclosureRegistry,
235) -> Result<(), String> {
236 if adapter.requires_specialized_fetch_path() {
237 return Err(
238 "this adapter consumes binary or multi-request data; use its typed async fetch API"
239 .into(),
240 );
241 }
242 let request = adapter.build_fetch_request(bbox, time_range, registry)?;
243 if adapter.needs_fetch_body() {
244 let body = execute_http_request_text_async(&request).await?;
245 adapter.handle_fetch_body(&body)
246 } else {
247 execute_http_request_text_async(&request).await.map(|_| ())
248 }
249}
250
251#[cfg(target_arch = "wasm32")]
255pub async fn fetch_region_features_async(
256 adapter: &dyn DataAdapter,
257 bbox: (f64, f64, f64, f64),
258 time_range: (u64, u64),
259 registry: &NetworkDisclosureRegistry,
260) -> Result<Vec<crate::NQuin>, String> {
261 if adapter.requires_specialized_fetch_path() {
262 return Err(
263 "this adapter consumes binary or multi-request data; use its typed async fetch API"
264 .into(),
265 );
266 }
267 let request = adapter.build_fetch_request(bbox, time_range, registry)?;
268 let body = execute_http_request_text_async(&request).await?;
269 adapter.parse_response(&body)
270}
271
272pub trait DataAdapter {
273 fn adapter_id(&self) -> &'static str;
275
276 fn build_fetch_request(
280 &self,
281 bbox: (f64, f64, f64, f64),
282 time_range: (u64, u64),
283 registry: &NetworkDisclosureRegistry,
284 ) -> Result<AdapterHttpRequest, String>;
285
286 fn fetch_region(
289 &self,
290 bbox: (f64, f64, f64, f64),
291 time_range: (u64, u64),
292 registry: &NetworkDisclosureRegistry,
293 ) -> Result<(), String> {
294 let request = self.build_fetch_request(bbox, time_range, registry)?;
295 if self.needs_fetch_body() {
296 let body = execute_http_request_text(&request)?;
297 self.handle_fetch_body(&body)
298 } else {
299 execute_http_request_status(&request)
300 }
301 }
302
303 fn needs_fetch_body(&self) -> bool {
306 false
307 }
308
309 fn requires_specialized_fetch_path(&self) -> bool {
312 false
313 }
314
315 fn handle_fetch_body(&self, _body: &str) -> Result<(), String> {
318 Ok(())
319 }
320
321 fn parse_response(&self, _body: &str) -> Result<Vec<crate::NQuin>, String> {
328 Ok(Vec::new())
329 }
330
331 fn fetch_region_features(
336 &self,
337 bbox: (f64, f64, f64, f64),
338 time_range: (u64, u64),
339 registry: &NetworkDisclosureRegistry,
340 ) -> Result<Vec<crate::NQuin>, String> {
341 let request = self.build_fetch_request(bbox, time_range, registry)?;
342 let body = execute_http_request_text(&request)?;
343 self.parse_response(&body)
344 }
345
346 fn primary_endpoint(&self) -> &str;
348
349 fn estimate_tile_count(&self, bbox: (f64, f64, f64, f64)) -> u32;
351}
352
353impl DataAdapter for DemAdapter {
354 fn adapter_id(&self) -> &'static str {
356 self.id
357 }
358
359 fn build_fetch_request(
361 &self,
362 bbox: (f64, f64, f64, f64),
363 time_range: (u64, u64),
364 registry: &NetworkDisclosureRegistry,
365 ) -> Result<AdapterHttpRequest, String> {
366 DemAdapter::build_fetch_request(self, bbox, time_range, registry)
367 }
368
369 fn needs_fetch_body(&self) -> bool {
371 true
372 }
373
374 fn requires_specialized_fetch_path(&self) -> bool {
376 true
377 }
378
379 fn handle_fetch_body(&self, _body: &str) -> Result<(), String> {
382 Err(
383 "Terrarium responses are binary PNG; call fetch_region_dem or fetch_region_dem_async"
384 .into(),
385 )
386 }
387
388 fn fetch_region(
391 &self,
392 bbox: (f64, f64, f64, f64),
393 _time_range: (u64, u64),
394 registry: &NetworkDisclosureRegistry,
395 ) -> Result<(), String> {
396 #[cfg(not(target_arch = "wasm32"))]
397 {
398 self.fetch_region_dem(bbox, registry).map(|_| ())
399 }
400 #[cfg(target_arch = "wasm32")]
401 {
402 let _ = (bbox, registry);
403 Err("use fetch_region_dem_async on wasm32 to fetch and compile terrain".into())
404 }
405 }
406
407 fn fetch_region_features(
410 &self,
411 bbox: (f64, f64, f64, f64),
412 _time_range: (u64, u64),
413 registry: &NetworkDisclosureRegistry,
414 ) -> Result<Vec<crate::NQuin>, String> {
415 #[cfg(not(target_arch = "wasm32"))]
416 {
417 self.fetch_region_dem(bbox, registry)
418 .map(|asset| asset.to_quins())
419 }
420 #[cfg(target_arch = "wasm32")]
421 {
422 let _ = (bbox, registry);
423 Err("use fetch_region_dem_async on wasm32 to receive the compiled terrain asset".into())
424 }
425 }
426
427 fn parse_response(&self, _body: &str) -> Result<Vec<crate::NQuin>, String> {
429 Err("Terrarium responses are binary PNG; call the typed DEM fetch method".into())
430 }
431
432 fn primary_endpoint(&self) -> &str {
434 self.endpoint.split("{z}").next().unwrap_or(&self.endpoint)
435 }
436
437 fn estimate_tile_count(&self, bbox: (f64, f64, f64, f64)) -> u32 {
439 DemAdapter::estimate_tile_count(self, bbox)
440 }
441}
442
443impl DataAdapter for OsmAdapter {
444 fn adapter_id(&self) -> &'static str {
446 "osm_adapter"
447 }
448
449 fn build_fetch_request(
451 &self,
452 bbox: (f64, f64, f64, f64),
453 time_range: (u64, u64),
454 registry: &NetworkDisclosureRegistry,
455 ) -> Result<AdapterHttpRequest, String> {
456 OsmAdapter::build_fetch_request(self, bbox, time_range, registry)
457 }
458
459 fn needs_fetch_body(&self) -> bool {
461 true
462 }
463
464 fn handle_fetch_body(&self, body: &str) -> Result<(), String> {
466 self.parse_vector_features(body).map(|_| ())
467 }
468
469 fn parse_response(&self, body: &str) -> Result<Vec<crate::NQuin>, String> {
471 self.parse_features(body)
472 }
473
474 fn primary_endpoint(&self) -> &str {
476 &self.overpass_endpoint
477 }
478
479 fn estimate_tile_count(&self, bbox: (f64, f64, f64, f64)) -> u32 {
481 1 + estimate_raster_tiles(bbox, 15)
483 }
484}
485
486impl DataAdapter for WmsAdapter {
487 fn adapter_id(&self) -> &'static str {
489 "wms_adapter"
490 }
491
492 fn build_fetch_request(
494 &self,
495 bbox: (f64, f64, f64, f64),
496 time_range: (u64, u64),
497 registry: &NetworkDisclosureRegistry,
498 ) -> Result<AdapterHttpRequest, String> {
499 WmsAdapter::build_fetch_request(self, bbox, time_range, registry)
500 }
501
502 fn primary_endpoint(&self) -> &str {
504 &self.endpoint
505 }
506
507 fn estimate_tile_count(&self, bbox: (f64, f64, f64, f64)) -> u32 {
509 estimate_raster_tiles(bbox, 12)
511 }
512}
513
514impl DataAdapter for GbifAdapter {
515 fn adapter_id(&self) -> &'static str {
517 "gbif_adapter"
518 }
519
520 fn build_fetch_request(
522 &self,
523 bbox: (f64, f64, f64, f64),
524 time_range: (u64, u64),
525 registry: &NetworkDisclosureRegistry,
526 ) -> Result<AdapterHttpRequest, String> {
527 GbifAdapter::build_fetch_request(self, bbox, time_range, registry)
528 }
529
530 fn primary_endpoint(&self) -> &str {
532 &self.occurrence_endpoint
533 }
534
535 fn estimate_tile_count(&self, bbox: (f64, f64, f64, f64)) -> u32 {
537 let area = (bbox.2 - bbox.0).abs() * (bbox.3 - bbox.1).abs();
539 let pages = (area * 10.0).ceil() as u32;
540 pages.max(1)
541 }
542}
543
544#[derive(Debug, Clone, PartialEq, Eq)]
546pub enum LayerFetchStatus {
547 ConsentDenied,
549 ReadyToFetch,
551 AdapterNotFound,
553}
554
555#[derive(Debug, Clone, PartialEq)]
557pub struct LayerFetchReport {
558 pub adapter_id: String,
559 pub endpoint: String,
560 pub bbox: (f64, f64, f64, f64),
561 pub time_range: (u64, u64),
562 pub estimated_tile_count: u32,
563 pub status: LayerFetchStatus,
564}
565
566pub struct AdapterRegistry {
568 adapters: HashMap<String, Box<dyn DataAdapter>>,
569 disclosure: NetworkDisclosureRegistry,
570}
571
572impl AdapterRegistry {
573 pub fn new() -> Self {
576 Self {
577 adapters: HashMap::new(),
578 disclosure: NetworkDisclosureRegistry::new(),
579 }
580 }
581
582 pub fn disclosure_registry(&self) -> &NetworkDisclosureRegistry {
584 &self.disclosure
585 }
586
587 pub fn disclosure_registry_mut(&mut self) -> &mut NetworkDisclosureRegistry {
589 &mut self.disclosure
590 }
591
592 pub fn register_adapter(&mut self, adapter: Box<dyn DataAdapter>) {
594 let id = adapter.adapter_id().to_string();
595 self.adapters.insert(id, adapter);
596 }
597
598 pub fn fetch_layer(
601 &self,
602 adapter_id: &str,
603 bbox: (f64, f64, f64, f64),
604 time_range: (u64, u64),
605 ) -> Result<LayerFetchReport, String> {
606 let adapter = self
607 .adapters
608 .get(adapter_id)
609 .ok_or_else(|| format!("Adapter '{}' not registered", adapter_id))?;
610
611 let endpoint = adapter.primary_endpoint().to_string();
612 let tile_count = adapter.estimate_tile_count(bbox);
613
614 let status = if self.disclosure.check_egress_consent(adapter_id, &endpoint) {
615 LayerFetchStatus::ReadyToFetch
616 } else {
617 LayerFetchStatus::ConsentDenied
618 };
619
620 Ok(LayerFetchReport {
621 adapter_id: adapter_id.to_string(),
622 endpoint,
623 bbox,
624 time_range,
625 estimated_tile_count: tile_count,
626 status,
627 })
628 }
629}
630
631impl Default for AdapterRegistry {
632 fn default() -> Self {
634 let mut registry = Self::new();
635 canvas_defaults::register_canvas_defaults(&mut registry);
636 registry
637 }
638}
639
640fn estimate_raster_tiles(bbox: (f64, f64, f64, f64), zoom: u8) -> u32 {
642 let (x1, y1, x2, y2) = bbox;
643 let n = 1u32 << zoom;
644 let tx1 = ((x1 + 180.0) / 360.0 * n as f64).floor() as u32;
645 let tx2 = ((x2 + 180.0) / 360.0 * n as f64).ceil() as u32;
646 let ty1 = ((1.0
647 - (y2.to_radians().tan() + 1.0 / y2.to_radians().cos()).ln() / std::f64::consts::PI)
648 / 2.0
649 * n as f64)
650 .floor() as u32;
651 let ty2 = ((1.0
652 - (y1.to_radians().tan() + 1.0 / y1.to_radians().cos()).ln() / std::f64::consts::PI)
653 / 2.0
654 * n as f64)
655 .ceil() as u32;
656 let tiles_x = tx2.saturating_sub(tx1).max(1);
657 let tiles_y = ty2.saturating_sub(ty1).max(1);
658 tiles_x.saturating_mul(tiles_y)
659}
660
661#[cfg(test)]
662mod tests {
663 use super::*;
664
665 #[test]
666 fn test_adapter_registry_consent_denied() {
667 let mut registry = AdapterRegistry::new();
668 registry.register_adapter(Box::new(DemAdapter::new(
669 "dem_adapter",
670 "https://elevation.example.com",
671 )));
672
673 let report = registry
674 .fetch_layer("dem_adapter", (0.0, 0.0, 1.0, 1.0), (0, 0))
675 .expect("report");
676
677 assert_eq!(report.status, LayerFetchStatus::ConsentDenied);
678 assert_eq!(report.endpoint, "https://elevation.example.com/terrarium/");
679 assert!(report.estimated_tile_count >= 1);
680 }
681
682 #[test]
683 fn test_adapter_registry_consent_granted() {
684 let mut registry = AdapterRegistry::new();
685 registry.register_adapter(Box::new(OsmAdapter::new(
686 "osm_adapter",
687 "https://overpass-api.de/api/interpreter",
688 "https://tiles.example.com/osm",
689 )));
690 registry.disclosure_registry_mut().register_egress(
691 "osm_adapter",
692 "https://overpass-api.de/api/interpreter",
693 "Fetch OSM features",
694 "User pans map",
695 );
696
697 let report = registry
698 .fetch_layer("osm_adapter", (-0.1, 51.4, 0.1, 51.6), (0, 0))
699 .expect("report");
700
701 assert_eq!(report.status, LayerFetchStatus::ReadyToFetch);
702 assert!(report.estimated_tile_count >= 1);
703 }
704
705 #[test]
706 fn test_adapter_registry_unknown_adapter() {
707 let registry = AdapterRegistry::new();
708 let err = registry
709 .fetch_layer("unknown_adapter", (0.0, 0.0, 1.0, 1.0), (0, 0))
710 .unwrap_err();
711 assert!(err.contains("not registered"));
712 }
713}