Skip to main content

solverforge_maps/routing/
cache.rs

1//! Zero-erasure cache for road networks.
2
3use std::collections::HashMap;
4use std::mem::size_of;
5use std::ops::Deref;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::Arc;
8use std::sync::OnceLock;
9
10use serde::{Deserialize, Serialize};
11use tokio::sync::{Mutex, RwLock, RwLockReadGuard};
12
13use super::bbox::BoundingBox;
14use super::config::RoadClass;
15use super::network::RoadNetwork;
16
17pub const CACHE_VERSION: u32 = 8;
18
19static NETWORK_CACHE: OnceLock<RwLock<HashMap<String, RoadNetwork>>> = OnceLock::new();
20static IN_FLIGHT_LOADS: OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> = OnceLock::new();
21static LOAD_REQUESTS: AtomicU64 = AtomicU64::new(0);
22static MEMORY_HITS: AtomicU64 = AtomicU64::new(0);
23static DISK_HITS: AtomicU64 = AtomicU64::new(0);
24static NETWORK_FETCHES: AtomicU64 = AtomicU64::new(0);
25static IN_FLIGHT_WAITS: AtomicU64 = AtomicU64::new(0);
26
27pub(crate) fn cache() -> &'static RwLock<HashMap<String, RoadNetwork>> {
28    NETWORK_CACHE.get_or_init(|| RwLock::new(HashMap::new()))
29}
30
31pub(crate) fn in_flight_loads() -> &'static Mutex<HashMap<String, Arc<Mutex<()>>>> {
32    IN_FLIGHT_LOADS.get_or_init(|| Mutex::new(HashMap::new()))
33}
34
35pub(crate) fn record_load_request() {
36    LOAD_REQUESTS.fetch_add(1, Ordering::Relaxed);
37}
38
39pub(crate) fn record_memory_hit() {
40    MEMORY_HITS.fetch_add(1, Ordering::Relaxed);
41}
42
43pub(crate) fn record_disk_hit() {
44    DISK_HITS.fetch_add(1, Ordering::Relaxed);
45}
46
47pub(crate) fn record_network_fetch() {
48    NETWORK_FETCHES.fetch_add(1, Ordering::Relaxed);
49}
50
51pub(crate) fn record_in_flight_wait() {
52    IN_FLIGHT_WAITS.fetch_add(1, Ordering::Relaxed);
53}
54
55#[cfg(test)]
56pub(crate) fn reset_cache_metrics() {
57    LOAD_REQUESTS.store(0, Ordering::Relaxed);
58    MEMORY_HITS.store(0, Ordering::Relaxed);
59    DISK_HITS.store(0, Ordering::Relaxed);
60    NETWORK_FETCHES.store(0, Ordering::Relaxed);
61    IN_FLIGHT_WAITS.store(0, Ordering::Relaxed);
62}
63
64#[derive(Debug, Clone)]
65pub struct CacheStats {
66    pub networks_cached: usize,
67    pub total_nodes: usize,
68    pub total_edges: usize,
69    pub memory_bytes: usize,
70    pub load_requests: u64,
71    pub memory_hits: u64,
72    pub disk_hits: u64,
73    pub network_fetches: u64,
74    pub in_flight_waits: u64,
75}
76
77/// RAII guard providing zero-cost access to a cached RoadNetwork.
78pub struct NetworkRef {
79    guard: RwLockReadGuard<'static, HashMap<String, RoadNetwork>>,
80    key: String,
81}
82
83impl Deref for NetworkRef {
84    type Target = RoadNetwork;
85
86    fn deref(&self) -> &RoadNetwork {
87        self.guard
88            .get(&self.key)
89            .expect("cached network disappeared")
90    }
91}
92
93impl NetworkRef {
94    pub(crate) fn new(
95        guard: RwLockReadGuard<'static, HashMap<String, RoadNetwork>>,
96        key: String,
97    ) -> Self {
98        debug_assert!(
99            guard.contains_key(&key),
100            "NetworkRef created for missing key"
101        );
102        Self { guard, key }
103    }
104
105    pub fn cache_key(&self) -> &str {
106        &self.key
107    }
108}
109
110#[derive(Debug, Serialize, Deserialize)]
111pub struct CachedNetwork {
112    pub version: u32,
113    pub nodes: Vec<CachedNode>,
114    pub edges: Vec<CachedEdge>,
115}
116
117#[derive(Debug, Serialize, Deserialize)]
118pub struct CachedNode {
119    pub lat: f64,
120    pub lng: f64,
121}
122
123#[derive(Debug, Serialize, Deserialize)]
124pub struct CachedEdge {
125    pub from: usize,
126    pub to: usize,
127    pub travel_time_s: f64,
128    pub distance_m: f64,
129    pub name: Option<String>,
130    pub road_class: RoadClass,
131}
132
133impl RoadNetwork {
134    pub async fn cache_stats() -> CacheStats {
135        let guard = cache().read().await;
136
137        let mut total_nodes = 0usize;
138        let mut total_edges = 0usize;
139        let mut memory_bytes = 0usize;
140
141        for network in guard.values() {
142            let nodes = network.node_count();
143            let edges = network.edge_count();
144            total_nodes += nodes;
145            total_edges += edges;
146
147            // Estimate memory: node data + edge data + hashmap overhead
148            memory_bytes += nodes * (size_of::<f64>() * 2 + size_of::<usize>() * 2);
149            memory_bytes += edges * (size_of::<f64>() * 2 + size_of::<usize>() * 2);
150        }
151
152        CacheStats {
153            networks_cached: guard.len(),
154            total_nodes,
155            total_edges,
156            memory_bytes,
157            load_requests: LOAD_REQUESTS.load(Ordering::Relaxed),
158            memory_hits: MEMORY_HITS.load(Ordering::Relaxed),
159            disk_hits: DISK_HITS.load(Ordering::Relaxed),
160            network_fetches: NETWORK_FETCHES.load(Ordering::Relaxed),
161            in_flight_waits: IN_FLIGHT_WAITS.load(Ordering::Relaxed),
162        }
163    }
164
165    pub async fn clear_cache() {
166        let mut guard = cache().write().await;
167        guard.clear();
168    }
169
170    pub async fn evict(bbox: &BoundingBox) -> bool {
171        let cache_key = bbox.cache_key();
172        let mut guard = cache().write().await;
173        guard.remove(&cache_key).is_some()
174    }
175
176    pub async fn cached_regions() -> Vec<BoundingBox> {
177        let guard = cache().read().await;
178        guard
179            .keys()
180            .filter_map(|key| parse_cache_key(key))
181            .collect()
182    }
183}
184
185/// The smallest cached area among `keys` that covers all of `bbox`: its roads serve any route
186/// inside it, so a smaller area inside one already loaded or saved needs no download.
187pub(crate) fn covering_key<'a>(
188    keys: impl IntoIterator<Item = &'a str>,
189    bbox: &BoundingBox,
190) -> Option<String> {
191    keys.into_iter()
192        .filter_map(|key| parse_cache_key(key).map(|area| (key, area)))
193        .filter(|(_, area)| area.contains_bbox(bbox))
194        .min_by(|(_, a), (_, b)| a.area().total_cmp(&b.area()))
195        .map(|(key, _)| key.to_string())
196}
197
198pub(crate) fn parse_cache_key(key: &str) -> Option<BoundingBox> {
199    let parts: Vec<&str> = key.split('_').collect();
200    if parts.len() != 4 {
201        return None;
202    }
203
204    let min_lat: f64 = parts[0].parse().ok()?;
205    let min_lng: f64 = parts[1].parse().ok()?;
206    let max_lat: f64 = parts[2].parse().ok()?;
207    let max_lng: f64 = parts[3].parse().ok()?;
208
209    BoundingBox::try_new(min_lat, min_lng, max_lat, max_lng).ok()
210}