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

Modern-Apps.git / scripts / maps / osm_ingest / src / poi_attrs.rs

poi_attrs.rs432 lines · 16.0 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
37use std::collections::HashMap;
38use std::io::{self, Write};
39
40pub const MAGIC: [u8; 4] = *b"MAPA";
41pub const VERSION: u8 = 1;
42/// magic + version + reserved + record_count.
43pub const HEADER_BYTES: usize = 12;
44/// `attr_off` value for a POI that carries none of the attributes we read.
45pub 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.
52pub const KEY_OPENING_HOURS: u8 = 1;
53pub const KEY_PHONE: u8 = 2;
54pub const KEY_WEBSITE: u8 = 3;
55pub const KEY_HOUSENUMBER: u8 = 4;
56pub const KEY_STREET: u8 = 5;
57pub const KEY_CITY: u8 = 6;
58pub const KEY_POSTCODE: u8 = 7;
59pub const KEY_CUISINE: u8 = 8;
60pub 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.
64pub const KEY_RATING: u8 = 10;
65pub const KEY_REVIEW_COUNT: u8 = 11;
66pub 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.
73pub 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.
90const 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.
97pub 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.iter().filter_map(|tag| get(tag)).find(|v| !v.is_empty()) else {
104 continue;
105 };
106 // A value too long to length-prefix is dropped rather than truncated: half a
107 // URL or half a phone number looks valid and is not.
108 let Ok(len) = u16::try_from(value.len()) else { continue };
109 if out.len() + 3 + value.len() > MAX_BODY_BYTES {
110 continue;
111 }
112 out.push(key);
113 out.extend_from_slice(&len.to_le_bytes());
114 out.extend_from_slice(value);
115 }
116 out
117}
118
119/// Append `(key, value)` fields after an [`encode`]d body.
120///
121/// `extra` must be ascending by key and every key must sort after the tag keys, so
122/// the record stays ascending. Empty values are skipped, and a value that would
123/// pass the body ceiling is dropped whole, under the same rules as [`encode`].
124pub fn append(mut body: Vec<u8>, extra: &[(u8, &[u8])]) -> Vec<u8> {
125 for &(key, value) in extra {
126 debug_assert!(key > KEY_WHEELCHAIR, "extra keys must sort after the tag keys");
127 if value.is_empty() {
128 continue;
129 }
130 let Ok(len) = u16::try_from(value.len()) else { continue };
131 if body.len() + 3 + value.len() > MAX_BODY_BYTES {
132 continue;
133 }
134 body.push(key);
135 body.extend_from_slice(&len.to_le_bytes());
136 body.extend_from_slice(value);
137 }
138 body
139}
140
141/// Deduplicating collector for the sidecar.
142///
143/// Holds the blob in memory, which is affordable only because `poi_build` already
144/// holds every POI — name and encoded attributes included — in memory to sort them.
145#[derive(Default)]
146pub struct AttrPool {
147 offsets: HashMap<Vec<u8>, u32>,
148 blob: Vec<u8>,
149 slots: Vec<u32>,
150}
151
152impl AttrPool {
153 pub fn new() -> Self {
154 Self::default()
155 }
156
157 /// Record the next POI's attributes. Call order IS the record ordinal.
158 pub fn push(&mut self, attrs: &[u8]) -> io::Result<()> {
159 if attrs.is_empty() {
160 self.slots.push(NO_ATTRS);
161 return Ok(());
162 }
163 if let Some(off) = self.offsets.get(attrs) {
164 self.slots.push(*off);
165 return Ok(());
166 }
167 let off =
168 u32::try_from(self.blob.len()).ok().filter(|o| *o != NO_ATTRS).ok_or_else(|| {
169 io::Error::new(
170 io::ErrorKind::InvalidData,
171 format!("attribute blob would pass {NO_ATTRS} bytes"),
172 )
173 })?;
174 // [`MAX_BODY_BYTES`] is enforced by `encode`, so this cannot fail for a body
175 // this crate produced. Reported rather than asserted because a wrong answer
176 // here would be a silently corrupt sidecar.
177 let len = u16::try_from(attrs.len()).map_err(|_| {
178 io::Error::new(
179 io::ErrorKind::InvalidData,
180 format!("attribute record of {} bytes is too long", attrs.len()),
181 )
182 })?;
183 self.blob.extend_from_slice(&len.to_le_bytes());
184 self.blob.extend_from_slice(attrs);
185 self.offsets.insert(attrs.to_vec(), off);
186 self.slots.push(off);
187 Ok(())
188 }
189
190 pub fn write(&self, out: &mut impl Write) -> io::Result<()> {
191 out.write_all(&MAGIC)?;
192 out.write_all(&[VERSION, 0, 0, 0])?;
193 let count = u32::try_from(self.slots.len()).map_err(|_| {
194 io::Error::new(io::ErrorKind::InvalidData, "more than u32::MAX POI records")
195 })?;
196 out.write_all(&count.to_le_bytes())?;
197 for off in &self.slots {
198 out.write_all(&off.to_le_bytes())?;
199 }
200 out.write_all(&self.blob)
201 }
202
203 /// POIs that carry at least one attribute.
204 pub fn with_attrs(&self) -> usize {
205 self.slots.iter().filter(|o| **o != NO_ATTRS).count()
206 }
207
208 /// Distinct attribute records stored, before the offset array.
209 pub fn unique_count(&self) -> usize {
210 self.offsets.len()
211 }
212
213 pub fn blob_len(&self) -> usize {
214 self.blob.len()
215 }
216
217 pub fn total_len(&self) -> usize {
218 HEADER_BYTES + 4 * self.slots.len() + self.blob.len()
219 }
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 /// Decode a record body back into `(key, value)` pairs, the way a reader must.
227 fn fields(body: &[u8]) -> Vec<(u8, String)> {
228 let mut out = Vec::new();
229 let mut i = 0;
230 while i + 3 <= body.len() {
231 let key = body[i];
232 let len = u16::from_le_bytes(body[i + 1..i + 3].try_into().unwrap()) as usize;
233 out.push((key, String::from_utf8(body[i + 3..i + 3 + len].to_vec()).unwrap()));
234 i += 3 + len;
235 }
236 out
237 }
238
239 fn tags<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<&'a [u8]> + 'a {
240 move |key: &str| pairs.iter().find(|(k, _)| *k == key).map(|(_, v)| v.as_bytes())
241 }
242
243 #[test]
244 fn a_poi_with_no_recognised_tags_encodes_to_nothing() {
245 assert!(encode(tags(&[("amenity", "cafe"), ("name", "Corner Cafe")])).is_empty());
246 }
247
248 #[test]
249 fn fields_come_out_in_ascending_key_order_whatever_the_tag_order() {
250 let body = encode(tags(&[
251 ("wheelchair", "yes"),
252 ("addr:street", "Market St"),
253 ("opening_hours", "24/7"),
254 ]));
255 assert_eq!(
256 fields(&body),
257 vec![
258 (KEY_OPENING_HOURS, "24/7".into()),
259 (KEY_STREET, "Market St".into()),
260 (KEY_WHEELCHAIR, "yes".into()),
261 ]
262 );
263 }
264
265 #[test]
266 fn the_preferred_tag_wins_over_its_contact_alias() {
267 let body = encode(tags(&[
268 ("contact:phone", "+1-555-0100"),
269 ("phone", "+1-555-0199"),
270 ("contact:website", "https://alias.example"),
271 ]));
272 assert_eq!(
273 fields(&body),
274 vec![(KEY_PHONE, "+1-555-0199".into()), (KEY_WEBSITE, "https://alias.example".into()),],
275 "phone from the preferred tag, website from the only one present"
276 );
277 }
278
279 #[test]
280 fn an_empty_tag_value_is_not_an_attribute() {
281 assert!(encode(tags(&[("phone", ""), ("website", "")])).is_empty());
282 }
283
284 #[test]
285 fn identical_records_are_stored_once_and_share_an_offset() {
286 let chain = encode(tags(&[("opening_hours", "Mo-Su 00:00-24:00")]));
287 let other = encode(tags(&[("opening_hours", "Mo-Fr 09:00-17:00")]));
288
289 let mut pool = AttrPool::new();
290 pool.push(&chain).unwrap();
291 pool.push(&[]).unwrap();
292 pool.push(&other).unwrap();
293 pool.push(&chain).unwrap();
294
295 assert_eq!(pool.slots, vec![0, NO_ATTRS, 2 + chain.len() as u32, 0]);
296 assert_eq!(pool.unique_count(), 2);
297 assert_eq!(pool.with_attrs(), 3);
298 }
299
300 #[test]
301 fn the_file_round_trips_through_its_own_layout() {
302 let hours = encode(tags(&[("opening_hours", "24/7"), ("phone", "+1-555-0100")]));
303 let mut pool = AttrPool::new();
304 pool.push(&[]).unwrap();
305 pool.push(&hours).unwrap();
306
307 let mut bytes = Vec::new();
308 pool.write(&mut bytes).unwrap();
309 assert_eq!(bytes.len(), pool.total_len());
310
311 assert_eq!(&bytes[0..4], &MAGIC);
312 assert_eq!(bytes[4], VERSION);
313 assert_eq!(&bytes[5..8], &[0, 0, 0], "reserved bytes are zero");
314 assert_eq!(u32::from_le_bytes(bytes[8..12].try_into().unwrap()), 2);
315
316 let off = |i: usize| {
317 let at = HEADER_BYTES + 4 * i;
318 u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
319 };
320 assert_eq!(off(0), NO_ATTRS, "the first POI has no attributes");
321
322 let blob = &bytes[HEADER_BYTES + 8..];
323 let at = off(1) as usize;
324 let len = u16::from_le_bytes(blob[at..at + 2].try_into().unwrap()) as usize;
325 assert_eq!(
326 fields(&blob[at + 2..at + 2 + len]),
327 vec![(KEY_OPENING_HOURS, "24/7".into()), (KEY_PHONE, "+1-555-0100".into()),]
328 );
329 }
330
331 /// The length prefixes exist so an older reader can step over a key it has
332 /// never heard of instead of losing everything after it.
333 #[test]
334 fn an_unknown_key_is_skippable_without_losing_the_rest() {
335 let mut body = encode(tags(&[("opening_hours", "24/7")]));
336 body.push(200); // a key from some future version
337 body.extend_from_slice(&3u16.to_le_bytes());
338 body.extend_from_slice(b"abc");
339 body.extend_from_slice(&encode(tags(&[("wheelchair", "yes")])));
340
341 let decoded = fields(&body);
342 assert_eq!(decoded.len(), 3);
343 assert_eq!(decoded[2], (KEY_WHEELCHAIR, "yes".into()));
344 }
345
346 #[test]
347 fn an_over_long_value_is_dropped_rather_than_truncated() {
348 let long = "x".repeat(70_000);
349 let body = encode(tags(&[("website", long.as_str()), ("wheelchair", "yes")]));
350 assert_eq!(
351 fields(&body),
352 vec![(KEY_WHEELCHAIR, "yes".into())],
353 "the long value is gone, the short one survives"
354 );
355 }
356
357 /// The `u16` length prefix in [`AttrPool::push`] is only infallible because
358 /// `encode` keeps the body under the ceiling, so one pathological element cannot
359 /// abort a planet build.
360 #[test]
361 fn a_body_that_would_pass_the_ceiling_drops_its_last_fields() {
362 let big = "x".repeat(60_000);
363 let body = encode(tags(&[
364 ("opening_hours", big.as_str()),
365 ("phone", big.as_str()),
366 ("wheelchair", "yes"),
367 ]));
368 assert!(body.len() <= MAX_BODY_BYTES);
369 assert_eq!(
370 fields(&body),
371 vec![
372 (KEY_OPENING_HOURS, big.clone()),
373 // `phone` would have pushed the body over, so it and nothing after it
374 // is written -- but `wheelchair` still fits after the skip.
375 (KEY_WHEELCHAIR, "yes".into()),
376 ]
377 );
378
379 let mut pool = AttrPool::new();
380 pool.push(&body).expect("a body encode produced is always writable");
381 }
382
383 /// An empty preferred tag must not shadow a populated alias.
384 #[test]
385 fn an_empty_preferred_tag_falls_through_to_its_alias() {
386 let body = encode(tags(&[("phone", ""), ("contact:phone", "+1-555-0100")]));
387 assert_eq!(fields(&body), vec![(KEY_PHONE, "+1-555-0100".into())]);
388 }
389
390 #[test]
391 fn review_fields_are_appended_after_the_tag_fields() {
392 let body = append(
393 encode(tags(&[("opening_hours", "24/7"), ("cuisine", "pizza")])),
394 &[
395 (KEY_RATING, b"4.3"),
396 (KEY_REVIEW_COUNT, b"1234"),
397 (KEY_REVIEW_SUMMARY, "Crisp crust, quick service.".as_bytes()),
398 ],
399 );
400 assert_eq!(
401 fields(&body),
402 vec![
403 (KEY_OPENING_HOURS, "24/7".into()),
404 (KEY_CUISINE, "pizza".into()),
405 (KEY_RATING, "4.3".into()),
406 (KEY_REVIEW_COUNT, "1234".into()),
407 (KEY_REVIEW_SUMMARY, "Crisp crust, quick service.".into()),
408 ]
409 );
410 }
411
412 #[test]
413 fn review_fields_alone_make_a_record_and_empty_ones_are_skipped() {
414 let body = append(
415 Vec::new(),
416 &[(KEY_RATING, b"4.0"), (KEY_REVIEW_COUNT, b""), (KEY_REVIEW_SUMMARY, b"")],
417 );
418 assert_eq!(fields(&body), vec![(KEY_RATING, "4.0".into())]);
419 assert!(append(Vec::new(), &[(KEY_REVIEW_SUMMARY, b"")]).is_empty());
420 }
421
422 #[test]
423 fn an_appended_value_past_the_ceiling_is_dropped_whole() {
424 let big = "x".repeat(65_000);
425 let body = append(
426 encode(tags(&[("opening_hours", big.as_str())])),
427 &[(KEY_RATING, b"4.5"), (KEY_REVIEW_SUMMARY, "y".repeat(1_000).as_bytes())],
428 );
429 assert!(body.len() <= MAX_BODY_BYTES);
430 assert_eq!(fields(&body).last().unwrap(), &(KEY_RATING, "4.5".into()));
431 }
432}