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