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};
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 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 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 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 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 speed = config.speed_profile.speed_mps(
284 tags.maxspeed.as_deref(),
285 tags.highway.as_deref().unwrap_or("residential"),
286 );
287
288 for window in node_ids.windows(2) {
289 let n1_id = window[0];
290 let n2_id = window[1];
291
292 let Some(&(lat1, lng1)) = nodes.get(&n1_id) else {
293 continue;
294 };
295 let Some(&(lat2, lng2)) = nodes.get(&n2_id) else {
296 continue;
297 };
298
299 let idx1 = *graph_nodes
300 .entry(n1_id)
301 .or_insert_with(|| network.add_node_at(lat1, lng1));
302 let idx2 = *graph_nodes
303 .entry(n2_id)
304 .or_insert_with(|| network.add_node_at(lat2, lng2));
305
306 let coord1 = Coord::new(lat1, lng1);
307 let coord2 = Coord::new(lat2, lng2);
308 let distance = super::geo::haversine_distance(coord1, coord2);
309 let travel_time = distance / speed;
310
311 let edge_data = EdgeData {
312 travel_time_s: travel_time,
313 distance_m: distance,
314 name: tags.name.clone(),
315 };
316
317 match direction {
318 TravelDirection::Forward => network.add_edge(idx1, idx2, edge_data),
319 TravelDirection::Backward => network.add_edge(idx2, idx1, edge_data),
320 TravelDirection::Both => {
321 network.add_edge(idx1, idx2, edge_data.clone());
322 network.add_edge(idx2, idx1, edge_data);
323 }
324 TravelDirection::None => unreachable!("skipped above"),
325 }
326 }
327
328 way_count += 1;
329 }
330 }
331 }
332
333 info!(
334 "Built graph with {} nodes and {} edges from {} ways",
335 network.node_count(),
336 network.edge_count(),
337 way_count
338 );
339
340 let scc_count = network.strongly_connected_components();
341 match config.connectivity_policy {
342 ConnectivityPolicy::KeepAll => {
343 if scc_count > 1 {
344 info!(
345 "Road network has {} SCCs, preserving all components by configuration",
346 scc_count
347 );
348 }
349 }
350 ConnectivityPolicy::LargestStronglyConnectedComponent => {
351 if scc_count > 1 {
352 info!(
353 "Road network has {} SCCs, filtering to largest component",
354 scc_count
355 );
356 network.filter_to_largest_scc();
357 info!(
358 "After SCC filter: {} nodes, {} edges",
359 network.node_count(),
360 network.edge_count()
361 );
362 }
363 }
364 }
365
366 network.build_spatial_index();
367
368 Ok(network)
369 }
370
371 async fn covering_file(dir: &Path, bbox: &BoundingBox) -> Option<std::path::PathBuf> {
373 let mut entries = tokio::fs::read_dir(dir).await.ok()?;
374 let mut keys = Vec::new();
375 while let Ok(Some(entry)) = entries.next_entry().await {
376 let name = entry.file_name();
377 if let Some(key) = name.to_str().and_then(|n| n.strip_suffix(".json")) {
378 keys.push(key.to_string());
379 }
380 }
381 covering_key(keys.iter().map(String::as_str), bbox)
382 .map(|key| dir.join(format!("{key}.json")))
383 }
384
385 async fn load_from_file(path: &Path, config: &NetworkConfig) -> Result<Self, RoutingError> {
386 let data = tokio::fs::read_to_string(path).await?;
387
388 let cached: CachedNetwork = match serde_json::from_str(&data) {
389 Ok(c) => c,
390 Err(e) => {
391 info!("Cache file corrupted, will re-download: {}", e);
392 let _ = tokio::fs::remove_file(path).await;
393 return Err(RoutingError::Parse(e.to_string()));
394 }
395 };
396
397 if cached.version != CACHE_VERSION {
398 info!(
399 "Cache version mismatch (got {}, need {}), will re-download",
400 cached.version, CACHE_VERSION
401 );
402 let _ = tokio::fs::remove_file(path).await;
403 return Err(RoutingError::Parse("cache version mismatch".into()));
404 }
405
406 let mut network = Self::new();
407
408 for node in &cached.nodes {
409 network.add_node_at(node.lat, node.lng);
410 }
411
412 for edge in &cached.edges {
413 network.add_edge_named_by_index(
414 edge.from,
415 edge.to,
416 edge.travel_time_s,
417 edge.distance_m,
418 edge.name.clone(),
419 );
420 }
421
422 let scc_count = network.strongly_connected_components();
423 match config.connectivity_policy {
424 ConnectivityPolicy::KeepAll => {
425 if scc_count > 1 {
426 info!(
427 "Cached network has {} SCCs, preserving all components by configuration",
428 scc_count
429 );
430 }
431 }
432 ConnectivityPolicy::LargestStronglyConnectedComponent => {
433 if scc_count > 1 {
434 info!(
435 "Cached network has {} SCCs, filtering to largest component",
436 scc_count
437 );
438 network.filter_to_largest_scc();
439 info!(
440 "After SCC filter: {} nodes, {} edges",
441 network.node_count(),
442 network.edge_count()
443 );
444 }
445 }
446 }
447
448 network.build_spatial_index();
449
450 Ok(network)
451 }
452
453 async fn save_to_file(&self, path: &Path) -> Result<(), RoutingError> {
454 let nodes: Vec<CachedNode> = self
455 .nodes_iter()
456 .map(|(lat, lng)| CachedNode { lat, lng })
457 .collect();
458
459 let edges: Vec<CachedEdge> = self
460 .edges_with_names_iter()
461 .map(|(from, to, travel_time_s, distance_m, name)| CachedEdge {
462 from,
463 to,
464 travel_time_s,
465 distance_m,
466 name,
467 })
468 .collect();
469
470 let cached = CachedNetwork {
471 version: CACHE_VERSION,
472 nodes,
473 edges,
474 };
475 let data =
476 serde_json::to_string(&cached).map_err(|e| RoutingError::Parse(e.to_string()))?;
477 tokio::fs::write(path, data).await?;
478
479 Ok(())
480 }
481
482 async fn load_or_insert<F>(cache_key: String, load: F) -> Result<NetworkRef, RoutingError>
483 where
484 F: Future<Output = Result<RoadNetwork, RoutingError>>,
485 {
486 if let Some(cached) = Self::get_cached_network(cache_key.clone()).await {
487 record_memory_hit();
488 return Ok(cached);
489 }
490
491 let (slot, _slot_guard, waited) = acquire_in_flight_slot(&cache_key).await;
492 if waited {
493 record_in_flight_wait();
494 }
495
496 if let Some(cached) = Self::get_cached_network(cache_key.clone()).await {
497 record_memory_hit();
498 cleanup_in_flight_slot(&cache_key, &slot).await;
499 return Ok(cached);
500 }
501
502 let network = load.await?;
503
504 {
505 let mut cache_guard = cache().write().await;
506 cache_guard.entry(cache_key.clone()).or_insert(network);
507 }
508
509 cleanup_in_flight_slot(&cache_key, &slot).await;
510
511 Self::get_cached_network(cache_key).await.ok_or_else(|| {
512 RoutingError::Network("cached network disappeared after insertion".to_string())
513 })
514 }
515
516 async fn get_cached_network(cache_key: String) -> Option<NetworkRef> {
517 let cache_guard = cache().read().await;
518 if cache_guard.contains_key(&cache_key) {
519 Some(NetworkRef::new(cache_guard, cache_key))
520 } else {
521 None
522 }
523 }
524}
525
526async fn fetch_overpass_bytes(
527 client: &reqwest::Client,
528 query: &str,
529 config: &NetworkConfig,
530 progress: Option<&Sender<RoutingProgress>>,
531) -> Result<Vec<u8>, RoutingError> {
532 let endpoints = overpass_endpoints(config);
533 let mut failures = Vec::new();
534
535 for (endpoint_index, endpoint) in endpoints.iter().enumerate() {
536 for attempt in 0..=config.overpass_max_retries {
537 info!(
538 "Sending request to Overpass API endpoint {} attempt {}: {}",
539 endpoint_index + 1,
540 attempt + 1,
541 endpoint
542 );
543
544 let response = client
545 .post(endpoint)
546 .body(query.to_owned())
547 .header("Content-Type", "text/plain")
548 .send()
549 .await;
550
551 match response {
552 Ok(response) if response.status().is_success() => {
553 info!(
554 "Received successful Overpass response from {} with status {}",
555 endpoint,
556 response.status()
557 );
558
559 if let Some(tx) = progress {
560 let _ = tx
561 .send(RoutingProgress::DownloadingNetwork {
562 percent: 25,
563 bytes: 0,
564 })
565 .await;
566 }
567
568 return response
569 .bytes()
570 .await
571 .map(|bytes| bytes.to_vec())
572 .map_err(|error| {
573 RoutingError::Network(format!(
574 "Overpass response body read failed from {} on attempt {}: {}",
575 endpoint,
576 attempt + 1,
577 error
578 ))
579 });
580 }
581 Ok(response) => {
582 let status = response.status();
583 failures.push(format!(
584 "{} attempt {} returned HTTP {}",
585 endpoint,
586 attempt + 1,
587 status
588 ));
589
590 if is_retryable_status(status) && attempt < config.overpass_max_retries {
591 sleep(retry_backoff(config.overpass_retry_backoff, attempt)).await;
592 continue;
593 }
594
595 break;
596 }
597 Err(error) => {
598 failures.push(format!(
599 "{} attempt {} failed: {}",
600 endpoint,
601 attempt + 1,
602 error
603 ));
604
605 if is_retryable_error(&error) && attempt < config.overpass_max_retries {
606 sleep(retry_backoff(config.overpass_retry_backoff, attempt)).await;
607 continue;
608 }
609
610 break;
611 }
612 }
613 }
614 }
615
616 Err(RoutingError::Network(format!(
617 "Overpass fetch failed after trying {} endpoint(s): {}",
618 endpoints.len(),
619 failures.join("; ")
620 )))
621}
622
623fn overpass_endpoints(config: &NetworkConfig) -> Vec<String> {
624 if config.overpass_endpoints.is_empty() {
625 vec![config.overpass_url.clone()]
626 } else {
627 config.overpass_endpoints.clone()
628 }
629}
630
631fn retry_backoff(base: Duration, attempt: usize) -> Duration {
632 base.saturating_mul((attempt + 1) as u32)
633}
634
635fn is_retryable_status(status: reqwest::StatusCode) -> bool {
636 status.is_server_error()
637 || status == reqwest::StatusCode::TOO_MANY_REQUESTS
638 || status == reqwest::StatusCode::REQUEST_TIMEOUT
639}
640
641fn is_retryable_error(error: &reqwest::Error) -> bool {
642 error.is_timeout() || error.is_connect() || error.is_request()
643}
644
645async fn acquire_in_flight_slot(cache_key: &str) -> (Arc<Mutex<()>>, OwnedMutexGuard<()>, bool) {
646 let slot = {
647 let mut in_flight = in_flight_loads().lock().await;
648 match in_flight.get(cache_key) {
649 Some(slot) => slot.clone(),
650 None => {
651 let slot = Arc::new(Mutex::new(()));
652 in_flight.insert(cache_key.to_string(), slot.clone());
653 slot
654 }
655 }
656 };
657
658 match slot.clone().try_lock_owned() {
659 Ok(guard) => (slot, guard, false),
660 Err(_) => {
661 let guard = slot.clone().lock_owned().await;
662 (slot, guard, true)
663 }
664 }
665}
666
667async fn cleanup_in_flight_slot(cache_key: &str, slot: &Arc<Mutex<()>>) {
668 let mut in_flight = in_flight_loads().lock().await;
669 let should_remove = in_flight
670 .get(cache_key)
671 .map(|current| Arc::ptr_eq(current, slot) && Arc::strong_count(slot) == 2)
672 .unwrap_or(false);
673
674 if should_remove {
675 in_flight.remove(cache_key);
676 }
677}
678
679#[cfg(test)]
680#[path = "fetch_tests.rs"]
681mod tests;