Skip to main content

qualia_core_db/domains/geospatial/adapters/
mod.rs

1//! Geospatial data adapters for integrating external layers into the canvas.
2
3pub 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    /// Build a GET request to `url` on behalf of `service_label`
50    /// (used in error messages).
51    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    /// Build a POST with `body` sent as
62    /// `application/x-www-form-urlencoded`.
63    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
74/// Format a timestamp range (seconds or milliseconds) into a standard ISO 8601 / RFC 3339 interval.
75pub 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/// Synchronous reqwest fetch returning the body as text (native only);
86/// errors name the `service_label` on non-2xx.
87#[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/// Synchronous reqwest fetch returning the body as bytes (native only)
114/// — the DEM/binary path.
115#[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/// Status-only variant — discards the body, keeps the success/error
144/// check (native only).
145#[cfg(not(target_arch = "wasm32"))]
146fn execute_http_request_status(request: &AdapterHttpRequest) -> Result<(), String> {
147    execute_http_request_text(request).map(|_| ())
148}
149
150/// Async reqwest fetch returning text (wasm32 only — the sync blocking
151/// client is unavailable there).
152#[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/// Async reqwest fetch returning bytes (wasm32 only).
178#[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/// wasm32 fail-closed variant: no blocking client exists, so callers
207/// are directed to the async fetch path.
208#[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/// wasm32 fail-closed variant: no blocking client exists, so callers
217/// are directed to the async fetch path.
218#[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/// wasm32 fetch path: consent-check via `registry`, issue the
227/// adapter's request, then hand the body to `handle_fetch_body`.
228/// Adapters needing binary/multi-request data are rejected up front.
229#[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/// Browser-safe fetch path that returns parsed graph features instead of
252/// dropping the response after validating it. Adapters which render typed
253/// geometry may additionally expose adapter-specific parsed outputs.
254#[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    /// Returns the unique identifier for this adapter (e.g., "dem_adapter")
274    fn adapter_id(&self) -> &'static str;
275
276    /// Build the outbound request for a spatial bounding box [x1, y1, x2, y2]
277    /// and temporal range [t0, t1]. Implementations must check `NetworkDisclosureRegistry`
278    /// before returning an actual network request.
279    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    /// Initiate fetching through the native blocking transport. Browser WASM
287    /// cannot legally block on network I/O, so wasm callers use `fetch_region_async`.
288    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    /// Whether the adapter consumes the response body instead of only checking
304    /// that the endpoint accepted the request.
305    fn needs_fetch_body(&self) -> bool {
306        false
307    }
308
309    /// Whether this adapter needs its typed fetch method for correct handling.
310    /// This prevents generic text transports from truncating tiled or binary data.
311    fn requires_specialized_fetch_path(&self) -> bool {
312        false
313    }
314
315    /// Parse or enqueue the fetched body. Most adapters currently only verify
316    /// access; CKAN consumes JSON discovery results here.
317    fn handle_fetch_body(&self, _body: &str) -> Result<(), String> {
318        Ok(())
319    }
320
321    /// Parse a fetched response body into provenance `NQuin`s (title / license /
322    /// created / source / lat / long, hashed with the same `generate_60bit_token`
323    /// the SPARQL layer uses, so the results are queryable). Adapters that can
324    /// interpret their response format override this — GBIF, OSM/Overpass, STAC,
325    /// OGC 3D Tiles and SPARQL-results do — and the default yields none. This is
326    /// how a fetched response becomes graph data rather than being discarded.
327    fn parse_response(&self, _body: &str) -> Result<Vec<crate::NQuin>, String> {
328        Ok(Vec::new())
329    }
330
331    /// Native fetch that returns the parsed provenance `NQuin`s: build the
332    /// consent-gated request, execute it, and run `parse_response` on the body.
333    /// A caller can then route the quins into the graph. (WASM callers fetch via
334    /// `fetch_region_async` and call `parse_response` on the returned body.)
335    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    /// Primary egress endpoint for disclosure checks and fetch reports.
347    fn primary_endpoint(&self) -> &str;
348
349    /// Honest estimate of how many tile/API units would be requested (no fake payloads).
350    fn estimate_tile_count(&self, bbox: (f64, f64, f64, f64)) -> u32;
351}
352
353impl DataAdapter for DemAdapter {
354    /// Registered adapter identifier (`self.id`).
355    fn adapter_id(&self) -> &'static str {
356        self.id
357    }
358
359    /// Build the Terrarium tile request via the inherent helper.
360    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    /// DEM responses are binary — the body must be consumed.
370    fn needs_fetch_body(&self) -> bool {
371        true
372    }
373
374    /// Binary PNG terrain can't go through the text pipeline.
375    fn requires_specialized_fetch_path(&self) -> bool {
376        true
377    }
378
379    /// Fail-closed: Terrarium responses are binary PNG; the typed DEM
380    /// fetch methods decode them.
381    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    /// Native: delegates to `fetch_region_dem` and discards the asset.
389    /// wasm32: fail-closed, directs callers to `fetch_region_dem_async`.
390    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    /// Native: `fetch_region_dem` compiled to NQuins. wasm32:
408    /// fail-closed, directs callers to `fetch_region_dem_async`.
409    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    /// Fail-closed: binary PNG cannot be parsed as text.
428    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    /// Endpoint URL with the `{z}` tile template truncated.
433    fn primary_endpoint(&self) -> &str {
434        self.endpoint.split("{z}").next().unwrap_or(&self.endpoint)
435    }
436
437    /// Tile estimate via the inherent helper.
438    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    /// `"osm_adapter"`.
445    fn adapter_id(&self) -> &'static str {
446        "osm_adapter"
447    }
448
449    /// Build the Overpass/MVT request via the inherent helper.
450    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    /// OSM vector data needs the response body.
460    fn needs_fetch_body(&self) -> bool {
461        true
462    }
463
464    /// Parse the response body as vector features (errors propagate).
465    fn handle_fetch_body(&self, body: &str) -> Result<(), String> {
466        self.parse_vector_features(body).map(|_| ())
467    }
468
469    /// Parse the body into feature NQuins via `parse_features`.
470    fn parse_response(&self, body: &str) -> Result<Vec<crate::NQuin>, String> {
471        self.parse_features(body)
472    }
473
474    /// The Overpass API endpoint.
475    fn primary_endpoint(&self) -> &str {
476        &self.overpass_endpoint
477    }
478
479    /// 1 Overpass query + z15 MVT tiles.
480    fn estimate_tile_count(&self, bbox: (f64, f64, f64, f64)) -> u32 {
481        // Overpass = 1 query + MVT tiles at z15
482        1 + estimate_raster_tiles(bbox, 15)
483    }
484}
485
486impl DataAdapter for WmsAdapter {
487    /// `"wms_adapter"`.
488    fn adapter_id(&self) -> &'static str {
489        "wms_adapter"
490    }
491
492    /// Build the WMS GetMap request via the inherent helper.
493    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    /// The WMS service endpoint.
503    fn primary_endpoint(&self) -> &str {
504        &self.endpoint
505    }
506
507    /// One GetMap per 256px tile at z12 viewport scale.
508    fn estimate_tile_count(&self, bbox: (f64, f64, f64, f64)) -> u32 {
509        // WMS GetMap: one request per 256px tile at typical viewport scale
510        estimate_raster_tiles(bbox, 12)
511    }
512}
513
514impl DataAdapter for GbifAdapter {
515    /// `"gbif_adapter"`.
516    fn adapter_id(&self) -> &'static str {
517        "gbif_adapter"
518    }
519
520    /// Build the GBIF occurrence request via the inherent helper.
521    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    /// The GBIF occurrence-search endpoint.
531    fn primary_endpoint(&self) -> &str {
532        &self.occurrence_endpoint
533    }
534
535    /// Page estimate: ~10 records/deg² at 300/page, minimum 1.
536    fn estimate_tile_count(&self, bbox: (f64, f64, f64, f64)) -> u32 {
537        // GBIF paginates at 300 records/page; estimate pages from bbox area (deg²).
538        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/// Status of a layer fetch plan — honest, no fabricated payloads.
545#[derive(Debug, Clone, PartialEq, Eq)]
546pub enum LayerFetchStatus {
547    /// Egress consent not registered; fail-closed.
548    ConsentDenied,
549    /// Consent granted; fetch would proceed (stub — no network I/O performed).
550    ReadyToFetch,
551    /// Adapter id not found in registry.
552    AdapterNotFound,
553}
554
555/// Structured report describing what a layer fetch *would* request.
556#[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
566/// Holds registered geospatial adapters and the network disclosure registry.
567pub struct AdapterRegistry {
568    adapters: HashMap<String, Box<dyn DataAdapter>>,
569    disclosure: NetworkDisclosureRegistry,
570}
571
572impl AdapterRegistry {
573    /// Empty registry with a fresh disclosure registry (no adapters —
574    /// use `Default` for the canvas built-ins).
575    pub fn new() -> Self {
576        Self {
577            adapters: HashMap::new(),
578            disclosure: NetworkDisclosureRegistry::new(),
579        }
580    }
581
582    /// The egress-consent registry (read).
583    pub fn disclosure_registry(&self) -> &NetworkDisclosureRegistry {
584        &self.disclosure
585    }
586
587    /// The egress-consent registry (mutable — grant/revoke consent).
588    pub fn disclosure_registry_mut(&mut self) -> &mut NetworkDisclosureRegistry {
589        &mut self.disclosure
590    }
591
592    /// Register `adapter` under its `adapter_id`.
593    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    /// Describe what would be fetched for a layer. Performs consent check; does not
599    /// initiate network I/O or return fabricated data.
600    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    /// Registry pre-populated with the canvas default adapters.
633    fn default() -> Self {
634        let mut registry = Self::new();
635        canvas_defaults::register_canvas_defaults(&mut registry);
636        registry
637    }
638}
639
640/// Rough Web-Mercator tile count estimate from a lon/lat bbox at a given zoom.
641fn 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}