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