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