Skip to main content

solverforge_maps/routing/
fetch.rs

1//! Overpass API fetching and caching for road networks.
2
3use std::collections::HashMap;
4use std::future::Future;
5use std::path::Path;
6use std::sync::Arc;
7use std::time::Duration;
8
9use tokio::sync::{mpsc::Sender, Mutex, OwnedMutexGuard};
10use tokio::time::sleep;
11use tracing::{debug, info};
12
13use super::bbox::BoundingBox;
14use super::cache::{
15    cache, covering_key, in_flight_loads, record_disk_hit, record_in_flight_wait,
16    record_load_request, record_memory_hit, record_network_fetch, CachedEdge, CachedNetwork,
17    CachedNode, NetworkRef, CACHE_VERSION,
18};
19use super::config::{ConnectivityPolicy, NetworkConfig, RoadClass};
20use super::coord::Coord;
21use super::error::RoutingError;
22use super::graph::NodeIdx;
23use super::network::{EdgeData, RoadNetwork};
24use super::osm::{OsmTags, OverpassResponse, TravelDirection};
25use super::progress::RoutingProgress;
26
27/// Identifies this crate and release to Overpass servers, whose usage policy
28/// requires a User-Agent that names the client. Built from the manifest so it
29/// follows every release.
30pub(crate) const USER_AGENT: &str = concat!(
31    env!("CARGO_PKG_NAME"),
32    "/",
33    env!("CARGO_PKG_VERSION"),
34    " (+",
35    env!("CARGO_PKG_REPOSITORY"),
36    ")"
37);
38
39impl RoadNetwork {
40    pub async fn load_or_fetch(
41        bbox: &BoundingBox,
42        config: &NetworkConfig,
43        progress: Option<&Sender<RoutingProgress>>,
44    ) -> Result<NetworkRef, RoutingError> {
45        let cache_key = bbox.cache_key();
46        record_load_request();
47
48        if let Some(tx) = progress {
49            let _ = tx.send(RoutingProgress::CheckingCache { percent: 0 }).await;
50        }
51
52        {
53            let cache_guard = cache().read().await;
54            if cache_guard.contains_key(&cache_key) {
55                record_memory_hit();
56                info!("Using in-memory cached road network for {}", cache_key);
57                if let Some(tx) = progress {
58                    let _ = tx
59                        .send(RoutingProgress::CheckingCache { percent: 10 })
60                        .await;
61                }
62                return Ok(NetworkRef::new(cache_guard, cache_key));
63            }
64            // A loaded network covering this whole area serves it as well.
65            if let Some(covering) = covering_key(cache_guard.keys().map(String::as_str), bbox) {
66                record_memory_hit();
67                info!(
68                    "Using in-memory road network {} covering {}",
69                    covering, cache_key
70                );
71                if let Some(tx) = progress {
72                    let _ = tx
73                        .send(RoutingProgress::CheckingCache { percent: 10 })
74                        .await;
75                }
76                return Ok(NetworkRef::new(cache_guard, covering));
77            }
78        }
79        if let Some(tx) = progress {
80            let _ = tx.send(RoutingProgress::CheckingCache { percent: 5 }).await;
81        }
82
83        Self::load_or_insert(cache_key, async {
84            tokio::fs::create_dir_all(&config.cache_dir).await?;
85            let cache_path = config.cache_dir.join(format!("{}.json", bbox.cache_key()));
86
87            if tokio::fs::try_exists(&cache_path).await.unwrap_or(false) {
88                info!("Loading road network from file cache: {:?}", cache_path);
89                if let Some(tx) = progress {
90                    let _ = tx.send(RoutingProgress::CheckingCache { percent: 8 }).await;
91                }
92                match Self::load_from_file(&cache_path, config).await {
93                    Ok(network) => {
94                        record_disk_hit();
95                        if let Some(tx) = progress {
96                            let _ = tx
97                                .send(RoutingProgress::BuildingGraph { percent: 50 })
98                                .await;
99                        }
100                        return Ok(network);
101                    }
102                    Err(e) => info!("File cache invalid ({}), downloading fresh", e),
103                }
104            } else if let Some(covering) = Self::covering_file(&config.cache_dir, bbox).await {
105                // A saved network for a larger area holds every road of this one.
106                info!(
107                    "Loading road network from covering file cache: {:?}",
108                    covering
109                );
110                if let Some(tx) = progress {
111                    let _ = tx.send(RoutingProgress::CheckingCache { percent: 8 }).await;
112                }
113                match Self::load_from_file(&covering, config).await {
114                    Ok(network) => {
115                        record_disk_hit();
116                        if let Some(tx) = progress {
117                            let _ = tx
118                                .send(RoutingProgress::BuildingGraph { percent: 50 })
119                                .await;
120                        }
121                        return Ok(network);
122                    }
123                    Err(e) => info!("Covering file cache invalid ({}), downloading fresh", e),
124                }
125            } else {
126                info!("Downloading road network from Overpass API");
127            }
128
129            record_network_fetch();
130            let network = Self::fetch_from_api(bbox, config, progress).await?;
131            network.save_to_file(&cache_path).await?;
132            info!("Saved road network to file cache: {:?}", cache_path);
133            Ok(network)
134        })
135        .await
136    }
137
138    pub async fn fetch(
139        bbox: &BoundingBox,
140        config: &NetworkConfig,
141        progress: Option<&Sender<RoutingProgress>>,
142    ) -> Result<Self, RoutingError> {
143        Self::fetch_from_api(bbox, config, progress).await
144    }
145
146    async fn fetch_from_api(
147        bbox: &BoundingBox,
148        config: &NetworkConfig,
149        progress: Option<&Sender<RoutingProgress>>,
150    ) -> Result<Self, RoutingError> {
151        let highway_regex = config.highway_regex();
152        let query = format!(
153            r#"[out:json][timeout:120];
154(
155  way["highway"~"{}"]
156    ({},{},{},{});
157);
158(._;>;);
159out body;"#,
160            highway_regex, bbox.min_lat, bbox.min_lng, bbox.max_lat, bbox.max_lng
161        );
162
163        debug!("Overpass query:\n{}", query);
164        info!(
165            "Preparing Overpass query for bbox: {:.4},{:.4} to {:.4},{:.4}",
166            bbox.min_lat, bbox.min_lng, bbox.max_lat, bbox.max_lng
167        );
168
169        if let Some(tx) = progress {
170            let _ = tx
171                .send(RoutingProgress::DownloadingNetwork {
172                    percent: 10,
173                    bytes: 0,
174                })
175                .await;
176        }
177
178        let client = reqwest::Client::builder()
179            .connect_timeout(config.connect_timeout)
180            .read_timeout(config.read_timeout)
181            .timeout(config.read_timeout)
182            .user_agent(USER_AGENT)
183            .build()
184            .map_err(|e| RoutingError::Network(e.to_string()))?;
185
186        if let Some(tx) = progress {
187            let _ = tx
188                .send(RoutingProgress::DownloadingNetwork {
189                    percent: 15,
190                    bytes: 0,
191                })
192                .await;
193        }
194
195        let bytes = fetch_overpass_bytes(&client, &query, config, progress).await?;
196
197        let bytes_len = bytes.len();
198        if let Some(tx) = progress {
199            let _ = tx
200                .send(RoutingProgress::DownloadingNetwork {
201                    percent: 30,
202                    bytes: bytes_len,
203                })
204                .await;
205        }
206
207        if let Some(tx) = progress {
208            let _ = tx
209                .send(RoutingProgress::ParsingOsm {
210                    percent: 32,
211                    nodes: 0,
212                    edges: 0,
213                })
214                .await;
215        }
216
217        let osm_data: OverpassResponse =
218            serde_json::from_slice(&bytes).map_err(|e| RoutingError::Parse(e.to_string()))?;
219
220        info!("Downloaded {} OSM elements", osm_data.elements.len());
221
222        if let Some(tx) = progress {
223            let _ = tx
224                .send(RoutingProgress::ParsingOsm {
225                    percent: 35,
226                    nodes: osm_data.elements.len(),
227                    edges: 0,
228                })
229                .await;
230        }
231
232        if let Some(tx) = progress {
233            let _ = tx
234                .send(RoutingProgress::BuildingGraph { percent: 40 })
235                .await;
236        }
237
238        let network = Self::build_from_osm(&osm_data, config)?;
239
240        if let Some(tx) = progress {
241            let _ = tx
242                .send(RoutingProgress::BuildingGraph { percent: 50 })
243                .await;
244            let _ = tx.send(RoutingProgress::Complete).await;
245        }
246
247        Ok(network)
248    }
249
250    pub(super) fn build_from_osm(
251        osm: &OverpassResponse,
252        config: &NetworkConfig,
253    ) -> Result<Self, RoutingError> {
254        let mut network = Self::new();
255
256        let mut nodes: HashMap<i64, (f64, f64)> = HashMap::new();
257        for elem in &osm.elements {
258            if elem.elem_type == "node" {
259                if let (Some(lat), Some(lon)) = (elem.lat, elem.lon) {
260                    nodes.insert(elem.id, (lat, lon));
261                }
262            }
263        }
264
265        info!("Parsed {} nodes", nodes.len());
266
267        // Graph nodes are OSM nodes. Two OSM nodes at the same position (a bridge
268        // over a road vertex) are not a junction and must not be joined.
269        let mut graph_nodes: HashMap<i64, NodeIdx> = HashMap::new();
270        let empty_tags = OsmTags::default();
271        let mut way_count = 0;
272        for elem in &osm.elements {
273            if elem.elem_type == "way" {
274                if let Some(ref node_ids) = elem.nodes {
275                    let tags = elem.tags.as_ref().unwrap_or(&empty_tags);
276                    if !tags.open_to_cars() {
277                        continue;
278                    }
279                    let direction = tags.travel_direction();
280                    if direction == TravelDirection::None {
281                        continue;
282                    }
283                    let highway = tags.highway.as_deref().unwrap_or("residential");
284                    let speed = config
285                        .speed_profile
286                        .speed_mps(tags.maxspeed.as_deref(), highway);
287                    let road_class = RoadClass::from_highway(highway);
288
289                    for window in node_ids.windows(2) {
290                        let n1_id = window[0];
291                        let n2_id = window[1];
292
293                        let Some(&(lat1, lng1)) = nodes.get(&n1_id) else {
294                            continue;
295                        };
296                        let Some(&(lat2, lng2)) = nodes.get(&n2_id) else {
297                            continue;
298                        };
299
300                        let idx1 = *graph_nodes
301                            .entry(n1_id)
302                            .or_insert_with(|| network.add_node_at(lat1, lng1));
303                        let idx2 = *graph_nodes
304                            .entry(n2_id)
305                            .or_insert_with(|| network.add_node_at(lat2, lng2));
306
307                        let coord1 = Coord::new(lat1, lng1);
308                        let coord2 = Coord::new(lat2, lng2);
309                        let distance = super::geo::haversine_distance(coord1, coord2);
310                        let travel_time = distance / speed;
311
312                        let edge_data = EdgeData {
313                            travel_time_s: travel_time,
314                            distance_m: distance,
315                            name: tags.name.clone(),
316                            road_class,
317                        };
318
319                        match direction {
320                            TravelDirection::Forward => network.add_edge(idx1, idx2, edge_data),
321                            TravelDirection::Backward => network.add_edge(idx2, idx1, edge_data),
322                            TravelDirection::Both => {
323                                network.add_edge(idx1, idx2, edge_data.clone());
324                                network.add_edge(idx2, idx1, edge_data);
325                            }
326                            TravelDirection::None => unreachable!("skipped above"),
327                        }
328                    }
329
330                    way_count += 1;
331                }
332            }
333        }
334
335        info!(
336            "Built graph with {} nodes and {} edges from {} ways",
337            network.node_count(),
338            network.edge_count(),
339            way_count
340        );
341
342        let scc_count = network.strongly_connected_components();
343        match config.connectivity_policy {
344            ConnectivityPolicy::KeepAll => {
345                if scc_count > 1 {
346                    info!(
347                        "Road network has {} SCCs, preserving all components by configuration",
348                        scc_count
349                    );
350                }
351            }
352            ConnectivityPolicy::LargestStronglyConnectedComponent => {
353                if scc_count > 1 {
354                    info!(
355                        "Road network has {} SCCs, filtering to largest component",
356                        scc_count
357                    );
358                    network.filter_to_largest_scc();
359                    info!(
360                        "After SCC filter: {} nodes, {} edges",
361                        network.node_count(),
362                        network.edge_count()
363                    );
364                }
365            }
366        }
367
368        network.build_spatial_index();
369
370        Ok(network)
371    }
372
373    /// The smallest saved network in `dir` whose area covers all of `bbox`.
374    async fn covering_file(dir: &Path, bbox: &BoundingBox) -> Option<std::path::PathBuf> {
375        let mut entries = tokio::fs::read_dir(dir).await.ok()?;
376        let mut keys = Vec::new();
377        while let Ok(Some(entry)) = entries.next_entry().await {
378            let name = entry.file_name();
379            if let Some(key) = name.to_str().and_then(|n| n.strip_suffix(".json")) {
380                keys.push(key.to_string());
381            }
382        }
383        covering_key(keys.iter().map(String::as_str), bbox)
384            .map(|key| dir.join(format!("{key}.json")))
385    }
386
387    async fn load_from_file(path: &Path, config: &NetworkConfig) -> Result<Self, RoutingError> {
388        let data = tokio::fs::read_to_string(path).await?;
389
390        let cached: CachedNetwork = match serde_json::from_str(&data) {
391            Ok(c) => c,
392            Err(e) => {
393                info!("Cache file corrupted, will re-download: {}", e);
394                let _ = tokio::fs::remove_file(path).await;
395                return Err(RoutingError::Parse(e.to_string()));
396            }
397        };
398
399        if cached.version != CACHE_VERSION {
400            info!(
401                "Cache version mismatch (got {}, need {}), will re-download",
402                cached.version, CACHE_VERSION
403            );
404            let _ = tokio::fs::remove_file(path).await;
405            return Err(RoutingError::Parse("cache version mismatch".into()));
406        }
407
408        let mut network = Self::new();
409
410        for node in &cached.nodes {
411            network.add_node_at(node.lat, node.lng);
412        }
413
414        for edge in &cached.edges {
415            network.add_edge_named_by_index(
416                edge.from,
417                edge.to,
418                edge.travel_time_s,
419                edge.distance_m,
420                edge.name.clone(),
421                edge.road_class,
422            );
423        }
424
425        let scc_count = network.strongly_connected_components();
426        match config.connectivity_policy {
427            ConnectivityPolicy::KeepAll => {
428                if scc_count > 1 {
429                    info!(
430                        "Cached network has {} SCCs, preserving all components by configuration",
431                        scc_count
432                    );
433                }
434            }
435            ConnectivityPolicy::LargestStronglyConnectedComponent => {
436                if scc_count > 1 {
437                    info!(
438                        "Cached network has {} SCCs, filtering to largest component",
439                        scc_count
440                    );
441                    network.filter_to_largest_scc();
442                    info!(
443                        "After SCC filter: {} nodes, {} edges",
444                        network.node_count(),
445                        network.edge_count()
446                    );
447                }
448            }
449        }
450
451        network.build_spatial_index();
452
453        Ok(network)
454    }
455
456    async fn save_to_file(&self, path: &Path) -> Result<(), RoutingError> {
457        let nodes: Vec<CachedNode> = self
458            .nodes_iter()
459            .map(|(lat, lng)| CachedNode { lat, lng })
460            .collect();
461
462        let edges: Vec<CachedEdge> = self
463            .graph
464            .edge_indices()
465            .filter_map(|idx| {
466                let (from, to) = self.graph.edge_endpoints(idx)?;
467                let edge = self.graph.edge_weight(idx)?;
468                Some(CachedEdge {
469                    from: from.index(),
470                    to: to.index(),
471                    travel_time_s: edge.travel_time_s,
472                    distance_m: edge.distance_m,
473                    name: edge.name.clone(),
474                    road_class: edge.road_class,
475                })
476            })
477            .collect();
478
479        let cached = CachedNetwork {
480            version: CACHE_VERSION,
481            nodes,
482            edges,
483        };
484        let data =
485            serde_json::to_string(&cached).map_err(|e| RoutingError::Parse(e.to_string()))?;
486        tokio::fs::write(path, data).await?;
487
488        Ok(())
489    }
490
491    async fn load_or_insert<F>(cache_key: String, load: F) -> Result<NetworkRef, RoutingError>
492    where
493        F: Future<Output = Result<RoadNetwork, RoutingError>>,
494    {
495        if let Some(cached) = Self::get_cached_network(cache_key.clone()).await {
496            record_memory_hit();
497            return Ok(cached);
498        }
499
500        let (slot, _slot_guard, waited) = acquire_in_flight_slot(&cache_key).await;
501        if waited {
502            record_in_flight_wait();
503        }
504
505        if let Some(cached) = Self::get_cached_network(cache_key.clone()).await {
506            record_memory_hit();
507            cleanup_in_flight_slot(&cache_key, &slot).await;
508            return Ok(cached);
509        }
510
511        let network = load.await?;
512
513        {
514            let mut cache_guard = cache().write().await;
515            cache_guard.entry(cache_key.clone()).or_insert(network);
516        }
517
518        cleanup_in_flight_slot(&cache_key, &slot).await;
519
520        Self::get_cached_network(cache_key).await.ok_or_else(|| {
521            RoutingError::Network("cached network disappeared after insertion".to_string())
522        })
523    }
524
525    async fn get_cached_network(cache_key: String) -> Option<NetworkRef> {
526        let cache_guard = cache().read().await;
527        if cache_guard.contains_key(&cache_key) {
528            Some(NetworkRef::new(cache_guard, cache_key))
529        } else {
530            None
531        }
532    }
533}
534
535async fn fetch_overpass_bytes(
536    client: &reqwest::Client,
537    query: &str,
538    config: &NetworkConfig,
539    progress: Option<&Sender<RoutingProgress>>,
540) -> Result<Vec<u8>, RoutingError> {
541    let endpoints = overpass_endpoints(config);
542    let mut failures = Vec::new();
543
544    for (endpoint_index, endpoint) in endpoints.iter().enumerate() {
545        for attempt in 0..=config.overpass_max_retries {
546            info!(
547                "Sending request to Overpass API endpoint {} attempt {}: {}",
548                endpoint_index + 1,
549                attempt + 1,
550                endpoint
551            );
552
553            let response = client
554                .post(endpoint)
555                .body(query.to_owned())
556                .header("Content-Type", "text/plain")
557                .send()
558                .await;
559
560            match response {
561                Ok(response) if response.status().is_success() => {
562                    info!(
563                        "Received successful Overpass response from {} with status {}",
564                        endpoint,
565                        response.status()
566                    );
567
568                    if let Some(tx) = progress {
569                        let _ = tx
570                            .send(RoutingProgress::DownloadingNetwork {
571                                percent: 25,
572                                bytes: 0,
573                            })
574                            .await;
575                    }
576
577                    return response
578                        .bytes()
579                        .await
580                        .map(|bytes| bytes.to_vec())
581                        .map_err(|error| {
582                            RoutingError::Network(format!(
583                                "Overpass response body read failed from {} on attempt {}: {}",
584                                endpoint,
585                                attempt + 1,
586                                error
587                            ))
588                        });
589                }
590                Ok(response) => {
591                    let status = response.status();
592                    failures.push(format!(
593                        "{} attempt {} returned HTTP {}",
594                        endpoint,
595                        attempt + 1,
596                        status
597                    ));
598
599                    if is_retryable_status(status) && attempt < config.overpass_max_retries {
600                        sleep(retry_backoff(config.overpass_retry_backoff, attempt)).await;
601                        continue;
602                    }
603
604                    break;
605                }
606                Err(error) => {
607                    failures.push(format!(
608                        "{} attempt {} failed: {}",
609                        endpoint,
610                        attempt + 1,
611                        error
612                    ));
613
614                    if is_retryable_error(&error) && attempt < config.overpass_max_retries {
615                        sleep(retry_backoff(config.overpass_retry_backoff, attempt)).await;
616                        continue;
617                    }
618
619                    break;
620                }
621            }
622        }
623    }
624
625    Err(RoutingError::Network(format!(
626        "Overpass fetch failed after trying {} endpoint(s): {}",
627        endpoints.len(),
628        failures.join("; ")
629    )))
630}
631
632fn overpass_endpoints(config: &NetworkConfig) -> Vec<String> {
633    if config.overpass_endpoints.is_empty() {
634        vec![config.overpass_url.clone()]
635    } else {
636        config.overpass_endpoints.clone()
637    }
638}
639
640fn retry_backoff(base: Duration, attempt: usize) -> Duration {
641    base.saturating_mul((attempt + 1) as u32)
642}
643
644fn is_retryable_status(status: reqwest::StatusCode) -> bool {
645    status.is_server_error()
646        || status == reqwest::StatusCode::TOO_MANY_REQUESTS
647        || status == reqwest::StatusCode::REQUEST_TIMEOUT
648}
649
650fn is_retryable_error(error: &reqwest::Error) -> bool {
651    error.is_timeout() || error.is_connect() || error.is_request()
652}
653
654async fn acquire_in_flight_slot(cache_key: &str) -> (Arc<Mutex<()>>, OwnedMutexGuard<()>, bool) {
655    let slot = {
656        let mut in_flight = in_flight_loads().lock().await;
657        match in_flight.get(cache_key) {
658            Some(slot) => slot.clone(),
659            None => {
660                let slot = Arc::new(Mutex::new(()));
661                in_flight.insert(cache_key.to_string(), slot.clone());
662                slot
663            }
664        }
665    };
666
667    match slot.clone().try_lock_owned() {
668        Ok(guard) => (slot, guard, false),
669        Err(_) => {
670            let guard = slot.clone().lock_owned().await;
671            (slot, guard, true)
672        }
673    }
674}
675
676async fn cleanup_in_flight_slot(cache_key: &str, slot: &Arc<Mutex<()>>) {
677    let mut in_flight = in_flight_loads().lock().await;
678    let should_remove = in_flight
679        .get(cache_key)
680        .map(|current| Arc::ptr_eq(current, slot) && Arc::strong_count(slot) == 2)
681        .unwrap_or(false);
682
683    if should_remove {
684        in_flight.remove(cache_key);
685    }
686}
687
688#[cfg(test)]
689#[path = "fetch_tests.rs"]
690mod tests;