Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / tilespill_part3.rs
tilespill_part3.rs440 lines · 19.5 KiBRaw
| 1 | #[cfg(test)] |
| 2 | mod tests { |
| 3 | use super::*; |
| 4 | use tilecodec::mamaps::body::{GEOM_LINE, GEOM_POLYGON, WINDING_HOLE, WINDING_OUTER}; |
| 5 | |
| 6 | pub(super) fn tmp(name: &str) -> PathBuf { |
| 7 | use std::sync::atomic::AtomicU64; |
| 8 | static NEXT: AtomicU64 = AtomicU64::new(0); |
| 9 | std::env::temp_dir().join(format!( |
| 10 | "mamaps_tilespill_{}_{}_{name}", |
| 11 | std::process::id(), |
| 12 | NEXT.fetch_add(1, Ordering::Relaxed), |
| 13 | )) |
| 14 | } |
| 15 | |
| 16 | pub(super) fn feature(kind: u16, detail: u16, geom: u8, flags: u8, at: u32, n: u32) -> BodyFeature { |
| 17 | BodyFeature { |
| 18 | kind, |
| 19 | kind_detail: detail, |
| 20 | geom_type: geom, |
| 21 | flags, |
| 22 | name_idx: tilecodec::mamaps::body::NAME_NONE, |
| 23 | parts_offset: at, |
| 24 | part_count: n, |
| 25 | transit_color: 0, |
| 26 | transit_ordinal: 0, |
| 27 | transit_lanes: 0, |
| 28 | transit_taper: 0, |
| 29 | lane_count: 0, |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | fn named(kind: u16, name_idx: u16) -> BodyFeature { |
| 34 | BodyFeature { |
| 35 | kind, |
| 36 | kind_detail: 0, |
| 37 | geom_type: tilecodec::mamaps::body::GEOM_POINT, |
| 38 | flags: 0, |
| 39 | name_idx, |
| 40 | parts_offset: 0, |
| 41 | part_count: 1, |
| 42 | transit_color: 0, |
| 43 | transit_ordinal: 0, |
| 44 | transit_lanes: 0, |
| 45 | transit_taper: 0, |
| 46 | lane_count: 0, |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | fn entry(layer_id: u8, features: Vec<BodyFeature>, names: &[&str]) -> ChunkEntry { |
| 51 | let mut layer = BodyLayer::new(layer_id); |
| 52 | layer.features = features; |
| 53 | for (i, _) in layer.features.iter().enumerate() { |
| 54 | layer.parts.push(Part { |
| 55 | coord_start: i as u32, |
| 56 | point_count: 1, |
| 57 | winding: WINDING_OUTER, |
| 58 | }); |
| 59 | layer.coords.push((i as i16, 0)); |
| 60 | } |
| 61 | // Fix up parts_offset to match the pushed parts (all features above use offset 0). |
| 62 | for (i, feature) in layer.features.iter_mut().enumerate() { |
| 63 | feature.parts_offset = i as u32; |
| 64 | } |
| 65 | ChunkEntry { layer, names: names.iter().map(|s| s.to_string()).collect(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), carriageways: Vec::new() } |
| 66 | } |
| 67 | |
| 68 | /// Every shape an entry can take, including the empty ones that a naive length check would let |
| 69 | /// through and a naive decode would trip on — plus a named entry, because names are the one |
| 70 | /// variable-length arena in the spill. |
| 71 | pub(super) fn every_layer() -> Vec<((u64, u8), ChunkEntry)> { |
| 72 | let plain = |layer_id: u8, features: Vec<BodyFeature>| ChunkEntry { |
| 73 | layer: BodyLayer { layer_id, features, parts: Vec::new(), coords: Vec::new() }, |
| 74 | names: Vec::new(), |
| 75 | ids: Vec::new(), |
| 76 | turn_lanes: Vec::new(), |
| 77 | buildings: Vec::new(), |
| 78 | carriageways: Vec::new(), |
| 79 | }; |
| 80 | vec![ |
| 81 | // Empty layer: no features, no parts, no coords. |
| 82 | ((1, 0), ChunkEntry::new(0)), |
| 83 | // Features but no parts and no coords, which `push` cannot make and a corrupt file can. |
| 84 | ((2, 1), plain(1, vec![feature(1, 2, GEOM_LINE, 0, 0, 0)])), |
| 85 | // A part with no coordinates. |
| 86 | ( |
| 87 | (3, 2), |
| 88 | ChunkEntry { |
| 89 | layer: BodyLayer { |
| 90 | layer_id: 2, |
| 91 | features: vec![feature(3, 4, GEOM_LINE, 1, 0, 1)], |
| 92 | parts: vec![Part { |
| 93 | coord_start: 0, |
| 94 | point_count: 0, |
| 95 | winding: WINDING_OUTER, |
| 96 | }], |
| 97 | coords: Vec::new(), |
| 98 | }, |
| 99 | names: Vec::new(), |
| 100 | ids: Vec::new(), |
| 101 | turn_lanes: Vec::new(), |
| 102 | buildings: Vec::new(), |
| 103 | carriageways: Vec::new(), |
| 104 | }, |
| 105 | ), |
| 106 | // The extremes of every field: `u16::MAX` kinds, `i16` at both ends, a hole. |
| 107 | ( |
| 108 | (4, 3), |
| 109 | ChunkEntry { |
| 110 | layer: BodyLayer { |
| 111 | layer_id: 3, |
| 112 | features: vec![ |
| 113 | feature(u16::MAX, u16::MAX, GEOM_POLYGON, 0x0f, 0, 2), |
| 114 | feature(0, 0, GEOM_POLYGON, 0, 2, 1), |
| 115 | ], |
| 116 | parts: vec![ |
| 117 | Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER }, |
| 118 | Part { coord_start: 2, point_count: 2, winding: WINDING_HOLE }, |
| 119 | Part { coord_start: 4, point_count: 1, winding: WINDING_OUTER }, |
| 120 | ], |
| 121 | coords: vec![ |
| 122 | (i16::MIN, i16::MAX), |
| 123 | (i16::MAX, i16::MIN), |
| 124 | (0, 0), |
| 125 | (-1, 1), |
| 126 | (32_767, -32_768), |
| 127 | ], |
| 128 | }, |
| 129 | names: Vec::new(), |
| 130 | ids: Vec::new(), |
| 131 | turn_lanes: Vec::new(), |
| 132 | buildings: Vec::new(), |
| 133 | carriageways: Vec::new(), |
| 134 | }, |
| 135 | ), |
| 136 | // Several layers on one tile, which is what the merge collapses. |
| 137 | ((5, 1), ChunkEntry::new(1)), |
| 138 | ( |
| 139 | (5, 7), |
| 140 | ChunkEntry { |
| 141 | layer: BodyLayer { |
| 142 | layer_id: 7, |
| 143 | features: vec![feature(9, 9, GEOM_LINE, 0, 0, 1)], |
| 144 | parts: vec![Part { |
| 145 | coord_start: 0, |
| 146 | point_count: 3, |
| 147 | winding: WINDING_OUTER, |
| 148 | }], |
| 149 | coords: vec![(1, 2), (3, 4), (5, 6)], |
| 150 | }, |
| 151 | names: Vec::new(), |
| 152 | ids: Vec::new(), |
| 153 | turn_lanes: Vec::new(), |
| 154 | buildings: Vec::new(), |
| 155 | carriageways: Vec::new(), |
| 156 | }, |
| 157 | ), |
| 158 | ((5, 10), ChunkEntry::new(10)), |
| 159 | // A named entry: two point labels sharing one name plus an unnamed one. |
| 160 | ((6, 8), entry(8, vec![named(3, 1), named(5, 1), named(7, 0)], &["Café"])), |
| 161 | // The id arena, which only `places` and `poi` carry: a real tagged OSM id, ID_NONE |
| 162 | // for a feature with no upstream element, and a value with its top bit set so a |
| 163 | // sign-extension bug in the u64 round trip cannot hide. |
| 164 | ( |
| 165 | (7, 8), |
| 166 | ChunkEntry { |
| 167 | ids: vec![ |
| 168 | crate::extract::tagged_id(240_109_189, crate::extract::ELEMENT_NODE), |
| 169 | tilecodec::mamaps::body::ID_NONE, |
| 170 | u64::MAX, |
| 171 | ], |
| 172 | ..entry(8, vec![named(3, 1), named(5, 0), named(7, 0)], &["Bar"]) |
| 173 | }, |
| 174 | ), |
| 175 | // The carriageway arena, which only `roads` carries: a divided road, a one-way with |
| 176 | // every lane forward, and a road whose split was never surveyed — all three in one |
| 177 | // entry, because the section is dense and the unsurveyed one still needs its slot. |
| 178 | ( |
| 179 | (8, 4), |
| 180 | ChunkEntry { |
| 181 | carriageways: vec![ |
| 182 | Carriageway { forward: 3, backward: 1, solid_dividers: 0b101 }, |
| 183 | Carriageway { forward: 2, backward: 0, solid_dividers: u32::MAX }, |
| 184 | Carriageway::default(), |
| 185 | ], |
| 186 | ..entry(4, vec![named(1, 0), named(2, 0), named(3, 0)], &[]) |
| 187 | }, |
| 188 | ), |
| 189 | ] |
| 190 | } |
| 191 | |
| 192 | pub(super) fn drain(spill: &ChunkSpill, at: &ChunkRef, window: usize) -> Vec<((u64, u8), ChunkEntry)> { |
| 193 | let mut reader = spill.reader(at, window); |
| 194 | let mut out = Vec::new(); |
| 195 | while let Some(entry) = reader.next().expect("read an entry back") { |
| 196 | out.push(entry); |
| 197 | } |
| 198 | out |
| 199 | } |
| 200 | |
| 201 | #[test] |
| 202 | fn a_chunk_round_trips_through_the_scratch_file() { |
| 203 | let spill = ChunkSpill::create(tmp("roundtrip")).expect("create"); |
| 204 | let want = every_layer(); |
| 205 | let map: BTreeMap<(u64, u8), ChunkEntry> = want.iter().cloned().collect(); |
| 206 | let at = spill.write_chunk(map).expect("write"); |
| 207 | assert_eq!(at.entries, want.len() as u64); |
| 208 | assert_eq!(drain(&spill, &at, 1 << 16), want); |
| 209 | spill.check_books().expect("the books balance"); |
| 210 | } |
| 211 | |
| 212 | /// **The silent one.** A `ChunkEntry.carriageways` that never reaches the spill is dropped on |
| 213 | /// every build that spills chunks — which is every real build — and the archive comes out with |
| 214 | /// no carriageway table, no lane markings and no error anywhere. Nothing else in this module |
| 215 | /// would notice: the books balance, the features are all there, and the map merely looks like |
| 216 | /// the renderer is at fault. |
| 217 | /// |
| 218 | /// So the section is asserted on its own rather than only inside `every_layer`: a road with a |
| 219 | /// divided carriageway, a one-way with every lane forward, and one whose split was never |
| 220 | /// surveyed — the last because the section is dense and its slot has to survive too. |
| 221 | #[test] |
| 222 | fn a_carriageway_section_survives_the_scratch_file() { |
| 223 | let spill = ChunkSpill::create(tmp("carriageways")).expect("create"); |
| 224 | let want = ChunkEntry { |
| 225 | carriageways: vec![ |
| 226 | Carriageway { forward: 3, backward: 1, solid_dividers: 0b101 }, |
| 227 | Carriageway { forward: 2, backward: 0, solid_dividers: u32::MAX }, |
| 228 | Carriageway::default(), |
| 229 | ], |
| 230 | ..entry(4, vec![named(1, 0), named(2, 0), named(3, 0)], &[]) |
| 231 | }; |
| 232 | let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new(); |
| 233 | map.insert((1, 4), want.clone()); |
| 234 | let at = spill.write_chunk(map).expect("write"); |
| 235 | let got = drain(&spill, &at, 1 << 16); |
| 236 | assert_eq!(got, vec![((1u64, 4u8), want)]); |
| 237 | // And the books, which are what would catch a section written but not accounted for. |
| 238 | spill.check_books().expect("the books balance"); |
| 239 | } |
| 240 | |
| 241 | /// A layer with no surveyed split writes no section at all, so a `boundaries` or `water` tile |
| 242 | /// pays nothing for a table that only roads ever have. |
| 243 | #[test] |
| 244 | fn an_entry_with_no_carriageways_writes_no_section() { |
| 245 | let spill = ChunkSpill::create(tmp("nocarriageways")).expect("create"); |
| 246 | let bare = entry(4, vec![named(1, 0), named(2, 0)], &[]); |
| 247 | let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new(); |
| 248 | map.insert((1, 4), bare.clone()); |
| 249 | let at = spill.write_chunk(map).expect("write"); |
| 250 | let with = ChunkEntry { |
| 251 | carriageways: vec![Carriageway::default(); 2], |
| 252 | ..entry(4, vec![named(1, 0), named(2, 0)], &[]) |
| 253 | }; |
| 254 | let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new(); |
| 255 | map.insert((1, 4), with); |
| 256 | let at_with = spill.write_chunk(map).expect("write"); |
| 257 | assert_eq!( |
| 258 | at_with.len - at.len, |
| 259 | 2 * CARRIAGEWAY_RECORD_LEN as u64, |
| 260 | "the section costs exactly one record per feature and nothing when absent", |
| 261 | ); |
| 262 | assert_eq!(drain(&spill, &at, 1 << 16), vec![((1u64, 4u8), bare)]); |
| 263 | } |
| 264 | |
| 265 | /// The read accounting survives a buffer compaction mid-entry. Names are pulled one inline |
| 266 | /// length at a time, so a narrow window tops the buffer up (compacting it) halfway through |
| 267 | /// an entry's names — and the bytes-read counter used to difference two offsets across that |
| 268 | /// compaction, undercounting by the compacted prefix. California z12 caught it: a megabyte |
| 269 | /// short on `check_books`. Narrow window + many long names forces the compaction here. |
| 270 | #[test] |
| 271 | fn a_narrow_window_compacting_mid_entry_still_balances_the_books() { |
| 272 | let spill = ChunkSpill::create(tmp("compactnames")).expect("create"); |
| 273 | let names: Vec<String> = (0..40).map(|i| format!("name-{i}-with-padding-to-lengthen")).collect(); |
| 274 | let features: Vec<BodyFeature> = names |
| 275 | .iter() |
| 276 | .enumerate() |
| 277 | .map(|(i, _)| BodyFeature { |
| 278 | kind: 1, |
| 279 | kind_detail: 0, |
| 280 | geom_type: tilecodec::mamaps::body::GEOM_POINT, |
| 281 | flags: 0, |
| 282 | name_idx: i as u16 + 1, |
| 283 | parts_offset: i as u32, |
| 284 | part_count: 1, |
| 285 | transit_color: 0, |
| 286 | transit_ordinal: 0, |
| 287 | transit_lanes: 0, |
| 288 | transit_taper: 0, |
| 289 | lane_count: 0, |
| 290 | }) |
| 291 | .collect(); |
| 292 | let mut layer = BodyLayer::new(8); |
| 293 | for (i, feature) in features.into_iter().enumerate() { |
| 294 | layer.features.push(feature); |
| 295 | layer.parts.push(Part { |
| 296 | coord_start: i as u32, |
| 297 | point_count: 1, |
| 298 | winding: WINDING_OUTER, |
| 299 | }); |
| 300 | layer.coords.push((i as i16, 0)); |
| 301 | } |
| 302 | let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new(); |
| 303 | map.insert((7, 8), ChunkEntry { layer, names: names.clone(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), carriageways: Vec::new() }); |
| 304 | let at = spill.write_chunk(map).expect("write"); |
| 305 | // Window of one header: every name tops up (and compacts) mid-entry. |
| 306 | let read = drain(&spill, &at, ENTRY_HEADER_BYTES); |
| 307 | assert_eq!(read.len(), 1); |
| 308 | assert_eq!(read[0].1.names, names); |
| 309 | spill.check_books().expect("the books balance after mid-entry compaction"); |
| 310 | } |
| 311 | |
| 312 | /// The claim the whole merge rests on: the file's order is `map.keys()`, so a reader hands |
| 313 | /// `Merged` the identical key sequence a `BTreeMap` did. |
| 314 | #[test] |
| 315 | fn entry_order_is_the_maps_key_order() { |
| 316 | let spill = ChunkSpill::create(tmp("order")).expect("create"); |
| 317 | // Inserted in a deliberately scrambled order; a `BTreeMap` sorts them and so must the file. |
| 318 | let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new(); |
| 319 | for (tile, layer) in [(30u64, 2u8), (10, 5), (10, 1), (20, 9), (10, 3), (30, 0)] { |
| 320 | map.insert((tile, layer), ChunkEntry::new(layer)); |
| 321 | } |
| 322 | let keys: Vec<(u64, u8)> = map.keys().copied().collect(); |
| 323 | let at = spill.write_chunk(map).expect("write"); |
| 324 | let read: Vec<(u64, u8)> = drain(&spill, &at, 1 << 16).into_iter().map(|(k, _)| k).collect(); |
| 325 | assert_eq!(read, keys); |
| 326 | assert_eq!(read, vec![(10, 1), (10, 3), (10, 5), (20, 9), (30, 0), (30, 2)]); |
| 327 | } |
| 328 | |
| 329 | /// Chunks written concurrently must not overlap, and every one must read back as itself. |
| 330 | #[test] |
| 331 | fn concurrent_chunks_get_disjoint_ranges_and_the_books_balance() { |
| 332 | let spill = ChunkSpill::create(tmp("concurrent")).expect("create"); |
| 333 | let refs: Vec<ChunkRef> = std::thread::scope(|scope| { |
| 334 | let handles: Vec<_> = (0..8u64) |
| 335 | .map(|i| { |
| 336 | scope.spawn({ |
| 337 | let spill = &spill; |
| 338 | move || { |
| 339 | let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new(); |
| 340 | for tile in 0..64u64 { |
| 341 | let mut entry = ChunkEntry::new(1); |
| 342 | entry.layer.coords = |
| 343 | vec![(i as i16, tile as i16); 1 + tile as usize]; |
| 344 | map.insert((tile, 1), entry); |
| 345 | } |
| 346 | (i, spill.write_chunk(map).expect("write")) |
| 347 | } |
| 348 | }) |
| 349 | }) |
| 350 | .collect(); |
| 351 | let mut refs: Vec<(u64, ChunkRef)> = |
| 352 | handles.into_iter().map(|h| h.join().expect("join")).collect(); |
| 353 | refs.sort_by_key(|(i, _)| *i); |
| 354 | refs.into_iter().map(|(_, at)| at).collect() |
| 355 | }); |
| 356 | |
| 357 | let mut ranges: Vec<(u64, u64)> = refs.iter().map(|r| (r.at, r.at + r.len)).collect(); |
| 358 | ranges.sort(); |
| 359 | for pair in ranges.windows(2) { |
| 360 | assert!(pair[0].1 <= pair[1].0, "two chunks share bytes: {pair:?}"); |
| 361 | } |
| 362 | for (i, at) in refs.iter().enumerate() { |
| 363 | let entries = drain(&spill, at, 1 << 15); |
| 364 | assert_eq!(entries.len(), 64); |
| 365 | assert_eq!(entries[3].1.layer.coords[0], (i as i16, 3)); |
| 366 | } |
| 367 | spill.check_books().expect("the books balance"); |
| 368 | } |
| 369 | |
| 370 | #[test] |
| 371 | fn a_truncated_chunk_errors_rather_than_decoding() { |
| 372 | let spill = ChunkSpill::create(tmp("truncated")).expect("create"); |
| 373 | let map: BTreeMap<(u64, u8), ChunkEntry> = every_layer().into_iter().collect(); |
| 374 | let at = spill.write_chunk(map).expect("write"); |
| 375 | |
| 376 | // Half a chunk: the reader is told the entry count but the bytes run out first. |
| 377 | let short = ChunkRef { at: at.at, len: at.len / 2, entries: at.entries }; |
| 378 | let mut reader = spill.reader(&short, 1 << 16); |
| 379 | let mut failed = false; |
| 380 | loop { |
| 381 | match reader.next() { |
| 382 | Ok(Some(_)) => {} |
| 383 | Ok(None) => break, |
| 384 | Err(_) => { |
| 385 | failed = true; |
| 386 | break; |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 | assert!(failed, "a truncated chunk decoded instead of erroring"); |
| 391 | |
| 392 | // And the other way round: the bytes are there but fewer entries were claimed, so the |
| 393 | // cursor would leave a tail behind. |
| 394 | let fewer = ChunkRef { at: at.at, len: at.len, entries: at.entries - 1 }; |
| 395 | let mut reader = spill.reader(&fewer, 1 << 16); |
| 396 | for _ in 0..fewer.entries { |
| 397 | reader.next().expect("read").expect("an entry"); |
| 398 | } |
| 399 | assert!(reader.next().is_err(), "a chunk with bytes past its last entry read as complete"); |
| 400 | } |
| 401 | |
| 402 | /// Byte 23 was the reserved tail and is now the carriageway flag, so the three section flags |
| 403 | /// are the whole of bytes 21..24. Each is 0 or 1: a spare value there means a newer writer put |
| 404 | /// something in it, and guessing would decode a section that moved. |
| 405 | #[test] |
| 406 | fn an_unknown_section_flag_errors() { |
| 407 | let head = [0u8; ENTRY_HEADER_BYTES]; |
| 408 | entry_header(&head).expect("a zero header is legal"); |
| 409 | for flag in 21..24 { |
| 410 | let mut set = head; |
| 411 | set[flag] = 1; |
| 412 | entry_header(&set).unwrap_or_else(|e| panic!("byte {flag} set is legal: {e:?}")); |
| 413 | let mut spare = head; |
| 414 | spare[flag] = 2; |
| 415 | assert!(entry_header(&spare).is_err(), "byte {flag} decoded a spare value"); |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | /// The word that was the second reserved tail is now the id count, and an id count that is |
| 420 | /// neither zero nor one-per-feature is a desynced side table — the one corruption that would |
| 421 | /// otherwise attribute every POI's id to its neighbour. |
| 422 | #[test] |
| 423 | fn an_id_count_that_does_not_match_the_features_errors() { |
| 424 | let mut head = [0u8; ENTRY_HEADER_BYTES]; |
| 425 | head[8..12].copy_from_slice(&2u32.to_le_bytes()); |
| 426 | head[28..32].copy_from_slice(&2u32.to_le_bytes()); |
| 427 | entry_header(&head).expect("one id per feature is legal"); |
| 428 | head[28..32].copy_from_slice(&0u32.to_le_bytes()); |
| 429 | entry_header(&head).expect("no ids at all is legal"); |
| 430 | head[28..32].copy_from_slice(&1u32.to_le_bytes()); |
| 431 | assert!(entry_header(&head).is_err(), "one id for two features decoded"); |
| 432 | } |
| 433 | |
| 434 | #[test] |
| 435 | fn an_entry_claiming_more_than_a_gigabyte_errors() { |
| 436 | let mut head = [0u8; ENTRY_HEADER_BYTES]; |
| 437 | head[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); |
| 438 | assert!(entry_header(&head).is_err(), "a gigabyte-plus entry decoded"); |
| 439 | } |
| 440 | } |