Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / poi_attrs.rs
poi_attrs.rs442 lines · 16.2 KiBRaw
| 1 | //! `poi_attrs.bin` — the attribute sidecar for `poi_index.bin`. |
| 2 | //! |
| 3 | //! `poi_index.bin`'s 14-byte record is fully packed, and its width is asserted in |
| 4 | //! three places (the writer, its test, and the README's `record_count = filesize / |
| 5 | //! 14`). So the OSM tag values that a place sheet wants — opening hours, phone, |
| 6 | //! website, address — go in a second file rather than a wider record. |
| 7 | //! |
| 8 | //! ## Indexed by record ordinal |
| 9 | //! |
| 10 | //! `attr_off[i]` describes the `i`th record of `poi_index.bin`. Not `osm_id`, which |
| 11 | //! is not in `poi_index.bin` at all, and not a coordinate: both files are written in |
| 12 | //! one pass over the same Morton-sorted POI vector, so ordinal alignment is free and |
| 13 | //! no join key has to be added to either format. |
| 14 | //! |
| 15 | //! ## Layout |
| 16 | //! |
| 17 | //! ```text |
| 18 | //! 0..4 magic b"MAPA" |
| 19 | //! 4 u8 version |
| 20 | //! 5..8 reserved, zero (keeps the offset array 4-aligned) |
| 21 | //! 8..12 u32 record_count |
| 22 | //! 12..12+4*record_count u32 attr_off[], a byte offset into the blob |
| 23 | //! below, or NO_ATTRS for a POI with no attributes |
| 24 | //! then the blob |
| 25 | //! ``` |
| 26 | //! |
| 27 | //! A blob record is a `u16` body length followed by that many bytes of |
| 28 | //! `u8 key, u16 value_len, value` triples, ascending by key. The length prefixes are |
| 29 | //! what let a reader built against version 1 skip a key added in version 2 instead |
| 30 | //! of losing the rest of the record — which is why the version byte does not gate |
| 31 | //! reading. |
| 32 | //! |
| 33 | //! Records are deduplicated whole, the way [`crate::names::NamePool`] dedupes names. |
| 34 | //! Chains repeat their whole attribute set, and `Mo-Su 00:00-24:00` is one of the |
| 35 | //! most common strings in OSM. |
| 36 | |
| 37 | use std::collections::HashMap; |
| 38 | use std::io::{self, Write}; |
| 39 | |
| 40 | pub const MAGIC: [u8; 4] = *b"MAPA"; |
| 41 | pub const VERSION: u8 = 1; |
| 42 | /// magic + version + reserved + record_count. |
| 43 | pub const HEADER_BYTES: usize = 12; |
| 44 | /// `attr_off` value for a POI that carries none of the attributes we read. |
| 45 | pub const NO_ATTRS: u32 = u32::MAX; |
| 46 | |
| 47 | /// Attribute keys. |
| 48 | /// |
| 49 | /// APPEND ONLY, and never renumber — exactly like the POI type enum. A code is |
| 50 | /// baked into every published sidecar, so reusing one relabels data already on |
| 51 | /// devices, and a device that has not updated has no way to tell. |
| 52 | pub const KEY_OPENING_HOURS: u8 = 1; |
| 53 | pub const KEY_PHONE: u8 = 2; |
| 54 | pub const KEY_WEBSITE: u8 = 3; |
| 55 | pub const KEY_HOUSENUMBER: u8 = 4; |
| 56 | pub const KEY_STREET: u8 = 5; |
| 57 | pub const KEY_CITY: u8 = 6; |
| 58 | pub const KEY_POSTCODE: u8 = 7; |
| 59 | pub const KEY_CUISINE: u8 = 8; |
| 60 | pub const KEY_WHEELCHAIR: u8 = 9; |
| 61 | /// Review data merged in from an external table at build time (see |
| 62 | /// [`crate::poi_reviews`]), never from OSM tags. ASCII decimal (`"4.3"`), ASCII |
| 63 | /// integer, and UTF-8 text. |
| 64 | pub const KEY_RATING: u8 = 10; |
| 65 | pub const KEY_REVIEW_COUNT: u8 = 11; |
| 66 | pub const KEY_REVIEW_SUMMARY: u8 = 12; |
| 67 | |
| 68 | /// Which OSM tags each key is read from, in the order they are encoded. |
| 69 | /// |
| 70 | /// Earlier tags win, so `phone` beats `contact:phone`. Kept deliberately short: |
| 71 | /// every key here costs bytes 22.6 million times over at planet scale, so a tag |
| 72 | /// earns its place by being something the place sheet actually shows. |
| 73 | pub const KEY_SOURCES: [(u8, &[&str]); 9] = [ |
| 74 | (KEY_OPENING_HOURS, &["opening_hours"]), |
| 75 | (KEY_PHONE, &["phone", "contact:phone"]), |
| 76 | (KEY_WEBSITE, &["website", "contact:website"]), |
| 77 | (KEY_HOUSENUMBER, &["addr:housenumber"]), |
| 78 | (KEY_STREET, &["addr:street"]), |
| 79 | (KEY_CITY, &["addr:city"]), |
| 80 | (KEY_POSTCODE, &["addr:postcode"]), |
| 81 | (KEY_CUISINE, &["cuisine"]), |
| 82 | (KEY_WHEELCHAIR, &["wheelchair"]), |
| 83 | ]; |
| 84 | |
| 85 | /// Largest record body we can length-prefix. |
| 86 | /// |
| 87 | /// Enforced by [`encode`] rather than checked by the writer, so the `u16` prefix in |
| 88 | /// [`AttrPool::push`] cannot fail: a single pathological OSM element must not abort a |
| 89 | /// planet build. |
| 90 | const MAX_BODY_BYTES: usize = u16::MAX as usize; |
| 91 | |
| 92 | /// Encode one POI's attribute record body, empty when it has none. |
| 93 | /// |
| 94 | /// `get` is called once per candidate tag in [`KEY_SOURCES`] order, so the output |
| 95 | /// depends only on the input tags — never on a hash map's iteration order, which |
| 96 | /// `two_runs_are_byte_identical` would catch. |
| 97 | pub fn encode<'a>(get: impl Fn(&str) -> Option<&'a [u8]>) -> Vec<u8> { |
| 98 | let mut out = Vec::new(); |
| 99 | for (key, sources) in KEY_SOURCES { |
| 100 | // The emptiness test goes inside the search, not after it: `phone=""` beside |
| 101 | // a real `contact:phone` must fall through to the alias rather than |
| 102 | // suppressing the key entirely. |
| 103 | let Some(value) = sources |
| 104 | .iter() |
| 105 | .filter_map(|tag| get(tag)) |
| 106 | .find(|v| !v.is_empty()) |
| 107 | else { |
| 108 | continue; |
| 109 | }; |
| 110 | // A value too long to length-prefix is dropped rather than truncated: half a |
| 111 | // URL or half a phone number looks valid and is not. |
| 112 | let Ok(len) = u16::try_from(value.len()) else { continue }; |
| 113 | if out.len() + 3 + value.len() > MAX_BODY_BYTES { |
| 114 | continue; |
| 115 | } |
| 116 | out.push(key); |
| 117 | out.extend_from_slice(&len.to_le_bytes()); |
| 118 | out.extend_from_slice(value); |
| 119 | } |
| 120 | out |
| 121 | } |
| 122 | |
| 123 | /// Append `(key, value)` fields after an [`encode`]d body. |
| 124 | /// |
| 125 | /// `extra` must be ascending by key and every key must sort after the tag keys, so |
| 126 | /// the record stays ascending. Empty values are skipped, and a value that would |
| 127 | /// pass the body ceiling is dropped whole, under the same rules as [`encode`]. |
| 128 | pub fn append(mut body: Vec<u8>, extra: &[(u8, &[u8])]) -> Vec<u8> { |
| 129 | for &(key, value) in extra { |
| 130 | debug_assert!(key > KEY_WHEELCHAIR, "extra keys must sort after the tag keys"); |
| 131 | if value.is_empty() { |
| 132 | continue; |
| 133 | } |
| 134 | let Ok(len) = u16::try_from(value.len()) else { continue }; |
| 135 | if body.len() + 3 + value.len() > MAX_BODY_BYTES { |
| 136 | continue; |
| 137 | } |
| 138 | body.push(key); |
| 139 | body.extend_from_slice(&len.to_le_bytes()); |
| 140 | body.extend_from_slice(value); |
| 141 | } |
| 142 | body |
| 143 | } |
| 144 | |
| 145 | /// Deduplicating collector for the sidecar. |
| 146 | /// |
| 147 | /// Holds the blob in memory, which is affordable only because `poi_build` already |
| 148 | /// holds every POI — name and encoded attributes included — in memory to sort them. |
| 149 | #[derive(Default)] |
| 150 | pub struct AttrPool { |
| 151 | offsets: HashMap<Vec<u8>, u32>, |
| 152 | blob: Vec<u8>, |
| 153 | slots: Vec<u32>, |
| 154 | } |
| 155 | |
| 156 | impl AttrPool { |
| 157 | pub fn new() -> Self { |
| 158 | Self::default() |
| 159 | } |
| 160 | |
| 161 | /// Record the next POI's attributes. Call order IS the record ordinal. |
| 162 | pub fn push(&mut self, attrs: &[u8]) -> io::Result<()> { |
| 163 | if attrs.is_empty() { |
| 164 | self.slots.push(NO_ATTRS); |
| 165 | return Ok(()); |
| 166 | } |
| 167 | if let Some(off) = self.offsets.get(attrs) { |
| 168 | self.slots.push(*off); |
| 169 | return Ok(()); |
| 170 | } |
| 171 | let off = u32::try_from(self.blob.len()) |
| 172 | .ok() |
| 173 | .filter(|o| *o != NO_ATTRS) |
| 174 | .ok_or_else(|| { |
| 175 | io::Error::new( |
| 176 | io::ErrorKind::InvalidData, |
| 177 | format!("attribute blob would pass {NO_ATTRS} bytes"), |
| 178 | ) |
| 179 | })?; |
| 180 | // [`MAX_BODY_BYTES`] is enforced by `encode`, so this cannot fail for a body |
| 181 | // this crate produced. Reported rather than asserted because a wrong answer |
| 182 | // here would be a silently corrupt sidecar. |
| 183 | let len = u16::try_from(attrs.len()).map_err(|_| { |
| 184 | io::Error::new( |
| 185 | io::ErrorKind::InvalidData, |
| 186 | format!("attribute record of {} bytes is too long", attrs.len()), |
| 187 | ) |
| 188 | })?; |
| 189 | self.blob.extend_from_slice(&len.to_le_bytes()); |
| 190 | self.blob.extend_from_slice(attrs); |
| 191 | self.offsets.insert(attrs.to_vec(), off); |
| 192 | self.slots.push(off); |
| 193 | Ok(()) |
| 194 | } |
| 195 | |
| 196 | pub fn write(&self, out: &mut impl Write) -> io::Result<()> { |
| 197 | out.write_all(&MAGIC)?; |
| 198 | out.write_all(&[VERSION, 0, 0, 0])?; |
| 199 | let count = u32::try_from(self.slots.len()).map_err(|_| { |
| 200 | io::Error::new(io::ErrorKind::InvalidData, "more than u32::MAX POI records") |
| 201 | })?; |
| 202 | out.write_all(&count.to_le_bytes())?; |
| 203 | for off in &self.slots { |
| 204 | out.write_all(&off.to_le_bytes())?; |
| 205 | } |
| 206 | out.write_all(&self.blob) |
| 207 | } |
| 208 | |
| 209 | /// POIs that carry at least one attribute. |
| 210 | pub fn with_attrs(&self) -> usize { |
| 211 | self.slots.iter().filter(|o| **o != NO_ATTRS).count() |
| 212 | } |
| 213 | |
| 214 | /// Distinct attribute records stored, before the offset array. |
| 215 | pub fn unique_count(&self) -> usize { |
| 216 | self.offsets.len() |
| 217 | } |
| 218 | |
| 219 | pub fn blob_len(&self) -> usize { |
| 220 | self.blob.len() |
| 221 | } |
| 222 | |
| 223 | pub fn total_len(&self) -> usize { |
| 224 | HEADER_BYTES + 4 * self.slots.len() + self.blob.len() |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | #[cfg(test)] |
| 229 | mod tests { |
| 230 | use super::*; |
| 231 | |
| 232 | /// Decode a record body back into `(key, value)` pairs, the way a reader must. |
| 233 | fn fields(body: &[u8]) -> Vec<(u8, String)> { |
| 234 | let mut out = Vec::new(); |
| 235 | let mut i = 0; |
| 236 | while i + 3 <= body.len() { |
| 237 | let key = body[i]; |
| 238 | let len = u16::from_le_bytes(body[i + 1..i + 3].try_into().unwrap()) as usize; |
| 239 | out.push((key, String::from_utf8(body[i + 3..i + 3 + len].to_vec()).unwrap())); |
| 240 | i += 3 + len; |
| 241 | } |
| 242 | out |
| 243 | } |
| 244 | |
| 245 | fn tags<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<&'a [u8]> + 'a { |
| 246 | move |key: &str| { |
| 247 | pairs |
| 248 | .iter() |
| 249 | .find(|(k, _)| *k == key) |
| 250 | .map(|(_, v)| v.as_bytes()) |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | #[test] |
| 255 | fn a_poi_with_no_recognised_tags_encodes_to_nothing() { |
| 256 | assert!(encode(tags(&[("amenity", "cafe"), ("name", "Corner Cafe")])).is_empty()); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn fields_come_out_in_ascending_key_order_whatever_the_tag_order() { |
| 261 | let body = encode(tags(&[ |
| 262 | ("wheelchair", "yes"), |
| 263 | ("addr:street", "Market St"), |
| 264 | ("opening_hours", "24/7"), |
| 265 | ])); |
| 266 | assert_eq!( |
| 267 | fields(&body), |
| 268 | vec![ |
| 269 | (KEY_OPENING_HOURS, "24/7".into()), |
| 270 | (KEY_STREET, "Market St".into()), |
| 271 | (KEY_WHEELCHAIR, "yes".into()), |
| 272 | ] |
| 273 | ); |
| 274 | } |
| 275 | |
| 276 | #[test] |
| 277 | fn the_preferred_tag_wins_over_its_contact_alias() { |
| 278 | let body = encode(tags(&[ |
| 279 | ("contact:phone", "+1-555-0100"), |
| 280 | ("phone", "+1-555-0199"), |
| 281 | ("contact:website", "https://alias.example"), |
| 282 | ])); |
| 283 | assert_eq!( |
| 284 | fields(&body), |
| 285 | vec![ |
| 286 | (KEY_PHONE, "+1-555-0199".into()), |
| 287 | (KEY_WEBSITE, "https://alias.example".into()), |
| 288 | ], |
| 289 | "phone from the preferred tag, website from the only one present" |
| 290 | ); |
| 291 | } |
| 292 | |
| 293 | #[test] |
| 294 | fn an_empty_tag_value_is_not_an_attribute() { |
| 295 | assert!(encode(tags(&[("phone", ""), ("website", "")])).is_empty()); |
| 296 | } |
| 297 | |
| 298 | #[test] |
| 299 | fn identical_records_are_stored_once_and_share_an_offset() { |
| 300 | let chain = encode(tags(&[("opening_hours", "Mo-Su 00:00-24:00")])); |
| 301 | let other = encode(tags(&[("opening_hours", "Mo-Fr 09:00-17:00")])); |
| 302 | |
| 303 | let mut pool = AttrPool::new(); |
| 304 | pool.push(&chain).unwrap(); |
| 305 | pool.push(&[]).unwrap(); |
| 306 | pool.push(&other).unwrap(); |
| 307 | pool.push(&chain).unwrap(); |
| 308 | |
| 309 | assert_eq!(pool.slots, vec![0, NO_ATTRS, 2 + chain.len() as u32, 0]); |
| 310 | assert_eq!(pool.unique_count(), 2); |
| 311 | assert_eq!(pool.with_attrs(), 3); |
| 312 | } |
| 313 | |
| 314 | #[test] |
| 315 | fn the_file_round_trips_through_its_own_layout() { |
| 316 | let hours = encode(tags(&[("opening_hours", "24/7"), ("phone", "+1-555-0100")])); |
| 317 | let mut pool = AttrPool::new(); |
| 318 | pool.push(&[]).unwrap(); |
| 319 | pool.push(&hours).unwrap(); |
| 320 | |
| 321 | let mut bytes = Vec::new(); |
| 322 | pool.write(&mut bytes).unwrap(); |
| 323 | assert_eq!(bytes.len(), pool.total_len()); |
| 324 | |
| 325 | assert_eq!(&bytes[0..4], &MAGIC); |
| 326 | assert_eq!(bytes[4], VERSION); |
| 327 | assert_eq!(&bytes[5..8], &[0, 0, 0], "reserved bytes are zero"); |
| 328 | assert_eq!(u32::from_le_bytes(bytes[8..12].try_into().unwrap()), 2); |
| 329 | |
| 330 | let off = |i: usize| { |
| 331 | let at = HEADER_BYTES + 4 * i; |
| 332 | u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) |
| 333 | }; |
| 334 | assert_eq!(off(0), NO_ATTRS, "the first POI has no attributes"); |
| 335 | |
| 336 | let blob = &bytes[HEADER_BYTES + 8..]; |
| 337 | let at = off(1) as usize; |
| 338 | let len = u16::from_le_bytes(blob[at..at + 2].try_into().unwrap()) as usize; |
| 339 | assert_eq!( |
| 340 | fields(&blob[at + 2..at + 2 + len]), |
| 341 | vec![ |
| 342 | (KEY_OPENING_HOURS, "24/7".into()), |
| 343 | (KEY_PHONE, "+1-555-0100".into()), |
| 344 | ] |
| 345 | ); |
| 346 | } |
| 347 | |
| 348 | /// The length prefixes exist so an older reader can step over a key it has |
| 349 | /// never heard of instead of losing everything after it. |
| 350 | #[test] |
| 351 | fn an_unknown_key_is_skippable_without_losing_the_rest() { |
| 352 | let mut body = encode(tags(&[("opening_hours", "24/7")])); |
| 353 | body.push(200); // a key from some future version |
| 354 | body.extend_from_slice(&3u16.to_le_bytes()); |
| 355 | body.extend_from_slice(b"abc"); |
| 356 | body.extend_from_slice(&encode(tags(&[("wheelchair", "yes")]))); |
| 357 | |
| 358 | let decoded = fields(&body); |
| 359 | assert_eq!(decoded.len(), 3); |
| 360 | assert_eq!(decoded[2], (KEY_WHEELCHAIR, "yes".into())); |
| 361 | } |
| 362 | |
| 363 | #[test] |
| 364 | fn an_over_long_value_is_dropped_rather_than_truncated() { |
| 365 | let long = "x".repeat(70_000); |
| 366 | let body = encode(tags(&[("website", long.as_str()), ("wheelchair", "yes")])); |
| 367 | assert_eq!( |
| 368 | fields(&body), |
| 369 | vec![(KEY_WHEELCHAIR, "yes".into())], |
| 370 | "the long value is gone, the short one survives" |
| 371 | ); |
| 372 | } |
| 373 | |
| 374 | /// The `u16` length prefix in [`AttrPool::push`] is only infallible because |
| 375 | /// `encode` keeps the body under the ceiling, so one pathological element cannot |
| 376 | /// abort a planet build. |
| 377 | #[test] |
| 378 | fn a_body_that_would_pass_the_ceiling_drops_its_last_fields() { |
| 379 | let big = "x".repeat(60_000); |
| 380 | let body = encode(tags(&[ |
| 381 | ("opening_hours", big.as_str()), |
| 382 | ("phone", big.as_str()), |
| 383 | ("wheelchair", "yes"), |
| 384 | ])); |
| 385 | assert!(body.len() <= MAX_BODY_BYTES); |
| 386 | assert_eq!( |
| 387 | fields(&body), |
| 388 | vec![ |
| 389 | (KEY_OPENING_HOURS, big.clone()), |
| 390 | // `phone` would have pushed the body over, so it and nothing after it |
| 391 | // is written -- but `wheelchair` still fits after the skip. |
| 392 | (KEY_WHEELCHAIR, "yes".into()), |
| 393 | ] |
| 394 | ); |
| 395 | |
| 396 | let mut pool = AttrPool::new(); |
| 397 | pool.push(&body).expect("a body encode produced is always writable"); |
| 398 | } |
| 399 | |
| 400 | /// An empty preferred tag must not shadow a populated alias. |
| 401 | #[test] |
| 402 | fn an_empty_preferred_tag_falls_through_to_its_alias() { |
| 403 | let body = encode(tags(&[("phone", ""), ("contact:phone", "+1-555-0100")])); |
| 404 | assert_eq!(fields(&body), vec![(KEY_PHONE, "+1-555-0100".into())]); |
| 405 | } |
| 406 | |
| 407 | #[test] |
| 408 | fn review_fields_are_appended_after_the_tag_fields() { |
| 409 | let body = append( |
| 410 | encode(tags(&[("opening_hours", "24/7"), ("cuisine", "pizza")])), |
| 411 | &[(KEY_RATING, b"4.3"), (KEY_REVIEW_COUNT, b"1234"), (KEY_REVIEW_SUMMARY, "Crisp crust, quick service.".as_bytes())], |
| 412 | ); |
| 413 | assert_eq!( |
| 414 | fields(&body), |
| 415 | vec![ |
| 416 | (KEY_OPENING_HOURS, "24/7".into()), |
| 417 | (KEY_CUISINE, "pizza".into()), |
| 418 | (KEY_RATING, "4.3".into()), |
| 419 | (KEY_REVIEW_COUNT, "1234".into()), |
| 420 | (KEY_REVIEW_SUMMARY, "Crisp crust, quick service.".into()), |
| 421 | ] |
| 422 | ); |
| 423 | } |
| 424 | |
| 425 | #[test] |
| 426 | fn review_fields_alone_make_a_record_and_empty_ones_are_skipped() { |
| 427 | let body = append(Vec::new(), &[(KEY_RATING, b"4.0"), (KEY_REVIEW_COUNT, b""), (KEY_REVIEW_SUMMARY, b"")]); |
| 428 | assert_eq!(fields(&body), vec![(KEY_RATING, "4.0".into())]); |
| 429 | assert!(append(Vec::new(), &[(KEY_REVIEW_SUMMARY, b"")]).is_empty()); |
| 430 | } |
| 431 | |
| 432 | #[test] |
| 433 | fn an_appended_value_past_the_ceiling_is_dropped_whole() { |
| 434 | let big = "x".repeat(65_000); |
| 435 | let body = append( |
| 436 | encode(tags(&[("opening_hours", big.as_str())])), |
| 437 | &[(KEY_RATING, b"4.5"), (KEY_REVIEW_SUMMARY, "y".repeat(1_000).as_bytes())], |
| 438 | ); |
| 439 | assert!(body.len() <= MAX_BODY_BYTES); |
| 440 | assert_eq!(fields(&body).last().unwrap(), &(KEY_RATING, "4.5".into())); |
| 441 | } |
| 442 | } |