Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / library / tilecodec / src / main / rust / tests / shared_leaf_cache.rs

shared_leaf_cache.rs198 lines · 6.8 KiBRaw
1//! Shared leaf cache: the issue-815 MapLibre-parity gate.
2//!
3//! The lib test target is broken at HEAD by in-progress header work (`shared_*`
4//! fields referenced from `mamaps::archive::tests` before they land on
5//! `Header`), so like `leaf_compression.rs` this exercises the public API only:
6//! it builds against the lib, never against `#[cfg(test)]` code.
7
8use std::sync::Arc;
9use tilecodec::mamaps::index::LeafEntry;
10use tilecodec::mamaps::read::{LeafCache, DEFAULT_LEAF_CACHE_CAPACITY};
11
12fn leaf(first: u32) -> Vec<LeafEntry> {
13 vec![LeafEntry {
14 tile_id_lo: first,
15 run_length: 1,
16 offset_delta: 0,
17 length: 8,
18 }]
19}
20
21#[test]
22fn an_inserted_leaf_reads_back() {
23 let cache = LeafCache::new();
24 assert_eq!(cache.capacity(), DEFAULT_LEAF_CACHE_CAPACITY);
25 assert!(cache.is_empty());
26 cache.insert(7, leaf(10));
27 assert_eq!(cache.len(), 1);
28 let hit = cache.get(7).expect("cached");
29 assert_eq!(hit.len(), 1);
30 assert_eq!(hit[0].tile_id_lo, 10);
31 assert!(cache.get(8).is_none(), "a miss is None");
32}
33
34#[test]
35fn the_cache_evicts_least_recently_used() {
36 let cache = LeafCache::with_capacity(2);
37 cache.insert(1, leaf(1));
38 cache.insert(2, leaf(2));
39 // Touch 1 so 2 is the eviction candidate.
40 let _ = cache.get(1);
41 cache.insert(3, leaf(3));
42 assert!(cache.get(1).is_some(), "recently used survives");
43 assert!(cache.get(2).is_none(), "least-recently-used is evicted");
44 assert!(cache.get(3).is_some());
45 assert_eq!(cache.len(), 2);
46}
47
48#[test]
49fn a_zero_capacity_still_holds_one_leaf() {
50 let cache = LeafCache::with_capacity(0);
51 assert_eq!(cache.capacity(), 1);
52 cache.insert(1, leaf(1));
53 assert!(cache.get(1).is_some());
54}
55
56#[test]
57fn a_racing_insert_keeps_one_copy() {
58 let cache = LeafCache::new();
59 let first = cache.insert(9, leaf(1));
60 let second = cache.insert(9, leaf(2));
61 assert!(Arc::ptr_eq(&first, &second), "the loser uses the winner's copy");
62 assert_eq!(cache.len(), 1);
63 assert_eq!(cache.get(9).expect("cached")[0].tile_id_lo, 1);
64}
65
66#[test]
67fn the_cache_shares_across_threads() {
68 let cache = Arc::new(LeafCache::new());
69 let mut handles = Vec::new();
70 for i in 0..8u64 {
71 let cache = Arc::clone(&cache);
72 handles.push(std::thread::spawn(move || {
73 cache.insert(i, leaf(i as u32));
74 // Every thread reads every leaf; concurrent gets are safe.
75 for j in 0..8u64 {
76 let _ = cache.get(j);
77 }
78 }));
79 }
80 for h in handles {
81 h.join().expect("worker");
82 }
83 assert_eq!(cache.len(), 8);
84 for i in 0..8u64 {
85 assert!(cache.get(i).is_some(), "leaf {i} survived the race");
86 }
87}
88
89/// Two archive views over one cache fetch a shared leaf once.
90///
91/// The cost contract the container exists to hold — open is one request, a
92/// warm tile one, a cold tile two — now holds *across* readers: the second
93/// view's tile costs one request (its body) because the first view's leaf
94/// fetch already populated the shared cache. Before the shared cache this
95/// second view paid two.
96#[test]
97fn two_archives_over_one_cache_fetch_a_shared_leaf_once() {
98 use tilecodec::mamaps::body::{Body, Feature, Layer, Part, DEFAULT_EXTENT, GEOM_LINE, WINDING_OUTER};
99 use tilecodec::mamaps::dict;
100 use tilecodec::mamaps::read::MamapsArchive;
101 use tilecodec::mamaps::write::{Options, StreamWriter};
102 use tilecodec::pmtiles::tile_id;
103 use tilecodec::proto::Result;
104 use tilecodec::stream::RangeReader;
105
106 struct Counting {
107 bytes: Vec<u8>,
108 requests: std::cell::RefCell<Vec<(u64, u32)>>,
109 }
110 impl RangeReader for Counting {
111 fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {
112 self.requests.borrow_mut().push((offset, length));
113 if offset >= self.bytes.len() as u64 {
114 return Ok(Vec::new());
115 }
116 let end = (offset + length as u64).min(self.bytes.len() as u64);
117 Ok(self.bytes[offset as usize..end as usize].to_vec())
118 }
119 }
120
121 fn body_for(seed: i16) -> Body {
122 let mut roads = Layer::new(dict::LAYER_ROADS);
123 roads.features.push(Feature {
124 kind: 45,
125 kind_detail: dict::NONE,
126 geom_type: GEOM_LINE,
127 flags: 0,
128 name_idx: tilecodec::mamaps::body::NAME_NONE,
129 parts_offset: 0,
130 part_count: 1,
131 transit_color: 0,
132 transit_ordinal: 0,
133 transit_lanes: 0,
134 transit_taper: 0,
135 lane_count: 0,
136 });
137 roads.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });
138 roads.coords = vec![(0, 0), (seed, seed)];
139 Body {
140 extent: DEFAULT_EXTENT,
141 layers: vec![roads],
142 names: Vec::new(),
143 ids: Vec::new(),
144 turn_lanes: Vec::new(),
145 buildings: Vec::new(),
146 heightmap: None,
147 carriageways: Vec::new(),
148 convention: None,
149 region_links: Vec::new(),
150 }
151 }
152
153 // Several leaves so a tile really has a leaf to share.
154 let mut tiles: Vec<(u8, u64, u64, i16)> = Vec::new();
155 for z in 0..=3u8 {
156 for x in 0..(1u64 << z) {
157 for y in 0..(1u64 << z) {
158 tiles.push((z, x, y, (tile_id(z, x, y) + 1) as i16));
159 }
160 }
161 }
162 let options = Options { leaf_entry_capacity: 16, ..Options::default() };
163 let mut rows: Vec<(u64, i16)> =
164 tiles.iter().map(|(z, x, y, seed)| (tile_id(*z, *x, *y), *seed)).collect();
165 rows.sort_by_key(|(id, _)| *id);
166 let mut writer = StreamWriter::new(options).expect("options");
167 for (id, seed) in rows {
168 writer.append(id, &body_for(seed)).expect("append");
169 }
170 let bytes = writer.finish().expect("finish");
171
172 let leaves = Arc::new(LeafCache::new());
173 let count = |a: &MamapsArchive<Counting>| a.reader().requests.borrow().len();
174
175 // First view: cold tile costs two (leaf + body).
176 let first = MamapsArchive::open_with_cache(
177 Counting { bytes: bytes.clone(), requests: std::cell::RefCell::new(Vec::new()) },
178 Arc::clone(&leaves),
179 )
180 .expect("open");
181 assert!(first.tile(3, 0, 0).expect("read").is_some());
182 assert_eq!(count(&first), 3, "open plus a cold tile: prefix, leaf, body");
183
184 // Second view over the same bytes and the same cache: the same tile costs
185 // one request (its body) — the leaf came from the shared cache, and the
186 // prefix open is its own one request.
187 let second = MamapsArchive::open_with_cache(
188 Counting { bytes, requests: std::cell::RefCell::new(Vec::new()) },
189 Arc::clone(&leaves),
190 )
191 .expect("open");
192 assert!(second.tile(3, 0, 0).expect("read").is_some());
193 assert_eq!(
194 count(&second),
195 2,
196 "open plus a shared-leaf tile: prefix and body, no second leaf fetch"
197 );
198}