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