Skip to main content

geolith/source/
osm.rs

1//! OSM PBF reader with two-pass processing.
2//!
3//! **Max node ID** ([`scan_max_node_id`]): sizes the node store, so a small
4//! regional extract does not allocate a 97 GB store. A PBF whose header
5//! declares `Sort.Type_then_ID` (Geofabrik extracts and the planet file) is
6//! answered from its last node blob, found by a binary search over blob
7//! headers; any other PBF gets a full parallel scan.
8//!
9//! **Pass 1** ([`pass1_nodes_and_relations`]): Single parallel scan that
10//! simultaneously collects every node coordinate into a dense [`NodeStore`]
11//! AND preprocesses boundary/route relations into a way→relation lookup.
12//! The node store is sized to fit the actual max node ID found during pre-scan.
13//!
14//! **Pass 2**: Process ways and relations into [`InputFeature`]s.
15//! Ways are reconstructed from node coordinates in the store.
16//! The pipeline uses parallel blob processing (`BlobReader::par_bridge`)
17//! for maximum throughput.
18
19use std::collections::HashMap;
20use std::path::Path;
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::sync::{Arc, Mutex, PoisonError};
23
24use osmpbf::{BlobReader, BlobType, ByteOffset, Element, ElementReader};
25
26use crate::source::input::{DataSource, InputFeature, OsmElementType, RelationInfo};
27use crate::source::node_store::NodeStore;
28use crate::tile::feature::PropValue;
29/// The largest node id a PBF may hold before it is rejected as corrupt:
30/// about 70 times the planet's 14.25 billion (October 2026).
31///
32/// The node store is sized from the real maximum ([`scan_max_node_id`]),
33/// never capped below it: a cap silently drops every newer node, and with
34/// them points of the ways through those nodes.
35const MAX_SANE_NODE_ID: u64 = 1 << 40;
36
37/// India bounding box for boundary suppression: [`min_lon`, `min_lat`, `max_lon`, `max_lat`].
38const INDIA_BBOX: [f64; 4] = [68.0, 6.5, 97.5, 37.2];
39
40/// Result of pass 1: statistics about nodes collected.
41pub struct NodeCollectionStats {
42    /// Total nodes stored.
43    pub nodes_stored: u64,
44    /// Maximum node ID that the store was allocated for.
45    pub max_node_id: u64,
46}
47
48/// Whether pass 1 collects the boundary and route relations of each way.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Relations {
51    /// Collect them: tiles read route refs and boundary admin levels.
52    Collect,
53    /// Skip them: geocoding reads no relation, and on a planet file the
54    /// way-to-relation map takes about 145 GB of memory.
55    Skip,
56}
57
58/// Result of pass 1: relation data collected alongside nodes.
59pub struct Pass1Result {
60    /// The populated node coordinate store.
61    pub store: NodeStore,
62    /// Statistics about nodes collected.
63    pub node_stats: NodeCollectionStats,
64    /// Map from way ID → relations that reference it (boundary/route).
65    pub way_to_relations: HashMap<i64, Vec<CollectedRelation>>,
66}
67
68/// The optional feature a PBF header sets when every node precedes every
69/// way and relation, and ids rise within each type.
70const SORTED_FEATURE: &str = "Sort.Type_then_ID";
71
72/// The largest node id of a PBF sorted by type then id, or `None` when the
73/// header does not declare that order.
74///
75/// In a sorted file the blobs that hold nodes are a prefix of the file, and
76/// the last node of the last of them has the largest id. Reading only the
77/// blob headers (each body is skipped with a seek), then binary-searching for
78/// that last node blob, decodes about `log2(blobs)` blobs: around 21 for the
79/// planet's 1.4 million, instead of every node blob.
80///
81/// # Errors
82///
83/// Returns an error if the PBF file can't be read or a blob can't be decoded.
84pub fn sorted_max_node_id(pbf_path: &Path) -> crate::error::Result<Option<u64>> {
85    let mut reader = BlobReader::seekable_from_path(pbf_path)?;
86    let mut header_offset = None;
87    let mut data_offsets: Vec<ByteOffset> = Vec::new();
88    while let Some(item) = reader.next_header_skip_blob() {
89        let (header, offset) = item?;
90        // A seekable reader reports the offset of every header it returns.
91        match (header.blob_type(), offset) {
92            (BlobType::OsmHeader, Some(offset)) if header_offset.is_none() => {
93                header_offset = Some(offset);
94            }
95            (BlobType::OsmData, Some(offset)) => data_offsets.push(offset),
96            _ => {}
97        }
98    }
99    let Some(header_offset) = header_offset else {
100        return Ok(None);
101    };
102    let header = reader.blob_from_offset(header_offset)?.to_headerblock()?;
103    let sorted = header
104        .optional_features()
105        .iter()
106        .chain(header.required_features())
107        .any(|f| f == SORTED_FEATURE);
108    if !sorted {
109        return Ok(None);
110    }
111
112    // The largest node id of blob `i`, or `None` if it holds no node.
113    let mut max_in = |i: usize| -> crate::error::Result<Option<u64>> {
114        let block = reader
115            .blob_from_offset(data_offsets[i])?
116            .to_primitiveblock()?;
117        let mut max: Option<i64> = None;
118        for group in block.groups() {
119            let ids = group
120                .dense_nodes()
121                .map(|n| n.id())
122                .chain(group.nodes().map(|n| n.id()));
123            for id in ids {
124                max = Some(max.map_or(id, |m| m.max(id)));
125            }
126        }
127        Ok(max.map(|m| m.max(0) as u64))
128    };
129
130    // The node blobs are `data_offsets[..end]`: find `end` by bisection. The
131    // last blob found to hold nodes is blob `end - 1`, so its max is the answer.
132    let (mut lo, mut hi) = (0usize, data_offsets.len());
133    let mut max_id = 0;
134    while lo < hi {
135        let mid = lo + (hi - lo) / 2;
136        match max_in(mid)? {
137            Some(max) => {
138                max_id = max;
139                lo = mid + 1;
140            }
141            None => hi = mid,
142        }
143    }
144    Ok(Some(max_id))
145}
146
147/// Find the maximum node ID of a PBF file.
148///
149/// A sorted PBF is answered by [`sorted_max_node_id`] without decoding the
150/// node blobs; any other PBF gets a parallel scan of every node, which for
151/// a planet PBF takes 2–3 minutes. The result sizes the node store, so a
152/// small extract does not allocate a 97 GB store.
153///
154/// An id above `MAX_SANE_NODE_ID` is an error, not a cap.
155///
156/// # Errors
157///
158/// Returns an error if the PBF file can't be read.
159pub fn scan_max_node_id(pbf_path: &Path) -> crate::error::Result<u64> {
160    require_osm_header(pbf_path)?;
161    let max_id = match sorted_max_node_id(pbf_path)? {
162        Some(max_id) => {
163            tracing::info!(
164                max_node_id = max_id,
165                "osm max node id read from the last node blob"
166            );
167            max_id
168        }
169        None => full_scan_max_node_id(pbf_path)?,
170    };
171    if max_id > MAX_SANE_NODE_ID {
172        return Err(crate::error::GeolithError::OsmPbf(format!(
173            "node id {max_id} is above {MAX_SANE_NODE_ID}; the PBF looks corrupt"
174        )));
175    }
176    Ok(max_id)
177}
178
179/// The first blob of an OSM PBF is its header. A file with no blob at all (an
180/// empty download) reads as a PBF with no elements, so the build would go on
181/// with an empty planet: refuse it, naming the file.
182///
183/// # Errors
184///
185/// `GeolithError::OsmPbf` when the file has no OSM header blob, the reader's
186/// error when the first blob cannot be read.
187pub fn require_osm_header(pbf_path: &Path) -> crate::error::Result<()> {
188    use osmpbf::{BlobDecode, BlobReader};
189    let mut blobs = BlobReader::from_path(pbf_path)?;
190    match blobs.next() {
191        Some(blob) => match blob?.decode()? {
192            BlobDecode::OsmHeader(_) => Ok(()),
193            _ => Err(crate::error::GeolithError::OsmPbf(format!(
194                "{} is not an OSM PBF: its first block is not the header",
195                pbf_path.display()
196            ))),
197        },
198        None => Err(crate::error::GeolithError::OsmPbf(format!(
199            "{} is not an OSM PBF: the file holds no block (empty or cut short; download it again)",
200            pbf_path.display()
201        ))),
202    }
203}
204
205/// Scan every node of a PBF for the largest id.
206fn full_scan_max_node_id(pbf_path: &Path) -> crate::error::Result<u64> {
207    let pb = crate::progress::phase_spinner("OSM pre-scan");
208    pb.set_message("finding max node ID...");
209
210    let reader = ElementReader::from_path(pbf_path)?;
211    let elements_scanned = AtomicU64::new(0);
212
213    let max_id = reader.par_map_reduce(
214        |element| {
215            let count = elements_scanned.fetch_add(1, Ordering::Relaxed) + 1;
216            if count.is_multiple_of(10_000_000) {
217                pb.set_message(format!("{count} elements scanned"));
218                tracing::info!("[osm_prescan] {count} elements scanned");
219            }
220            match element {
221                Element::DenseNode(node) => node.id.max(0) as u64,
222                Element::Node(node) => node.id().max(0) as u64,
223                _ => 0,
224            }
225        },
226        || 0_u64,
227        |a, b| a.max(b),
228    )?;
229
230    pb.finish_with_message(format!(
231        "done: max node ID = {} ({:.1} GB node store)",
232        max_id,
233        (max_id + 1) as f64 * 8.0 / 1_073_741_824.0,
234    ));
235    tracing::info!(max_node_id = max_id, "osm prescan done");
236    Ok(max_id)
237}
238
239/// Keep the first failed node-store write in `slot`.
240fn record_write(
241    slot: &Mutex<Option<crate::error::GeolithError>>,
242    result: crate::error::Result<()>,
243) {
244    if let Err(e) = result {
245        slot.lock()
246            .unwrap_or_else(PoisonError::into_inner)
247            .get_or_insert(e);
248    }
249}
250
251/// Run pass 1: collect nodes AND preprocess relations in a single PBF read.
252///
253/// First finds the maximum node ID ([`scan_max_node_id`]), then allocates
254/// the node store to fit. This avoids a 97 GB mmap for small regional
255/// extracts while still supporting planet-scale builds.
256///
257/// # Errors
258///
259/// Returns an error if the PBF file can't be read or node store can't be created.
260pub fn pass1_nodes_and_relations(
261    pbf_path: &Path,
262    store_path: &Path,
263    force_dense: bool,
264    relations: Relations,
265) -> crate::error::Result<Pass1Result> {
266    // Size the store to the real max node ID (avoids a 97 GB mmap for small extracts).
267    let max_node_id = scan_max_node_id(pbf_path)?;
268
269    let pb = crate::progress::phase_spinner("OSM pass 1");
270    pb.set_message("collecting nodes + relations...");
271
272    tracing::info!("Allocating node store for {} max node ID", max_node_id);
273
274    let mut store = NodeStore::create(store_path, max_node_id, force_dense)?;
275    let writer = store.concurrent_writer()?;
276    let reader = ElementReader::from_path(pbf_path)?;
277    let elements_processed = AtomicU64::new(0);
278    // The first node-store write failure; `par_map_reduce` cannot stop early.
279    let write_error: Mutex<Option<crate::error::GeolithError>> = Mutex::new(None);
280
281    // Per-thread accumulator: (nodes_stored, way→relations map)
282    let (total_stored, mut way_to_relations) = reader.par_map_reduce(
283        |element| {
284            let count = elements_processed.fetch_add(1, Ordering::Relaxed) + 1;
285            if count.is_multiple_of(10_000_000) {
286                pb.set_message(format!("{count} elements processed"));
287                tracing::info!("[osm_pass1] {count} elements processed");
288            }
289            let mut local_nodes = 0_u64;
290            let mut local_map: HashMap<i64, Vec<CollectedRelation>> = HashMap::new();
291
292            match element {
293                Element::DenseNode(node) => {
294                    record_write(
295                        &write_error,
296                        writer.put(node.id as u64, node.lat(), node.lon()),
297                    );
298                    local_nodes = 1;
299                }
300                Element::Node(node) => {
301                    record_write(
302                        &write_error,
303                        writer.put(node.id() as u64, node.lat(), node.lon()),
304                    );
305                    local_nodes = 1;
306                }
307                Element::Relation(rel) if relations == Relations::Collect => {
308                    let tags: HashMap<String, String> = rel
309                        .tags()
310                        .map(|(k, v)| (k.to_string(), v.to_string()))
311                        .collect();
312
313                    let is_boundary = tags.get("type").is_some_and(|t| t == "boundary")
314                        || tags.contains_key("boundary");
315                    let is_route = tags.get("type").is_some_and(|t| t == "route");
316
317                    if is_boundary || is_route {
318                        let rel_id = rel.id();
319
320                        let way_member_ids: Vec<i64> = rel
321                            .members()
322                            .filter(|m| m.member_type == osmpbf::elements::RelMemberType::Way)
323                            .map(|m| m.member_id)
324                            .collect();
325
326                        for way_id in &way_member_ids {
327                            local_map
328                                .entry(*way_id)
329                                .or_default()
330                                .push(CollectedRelation {
331                                    id: rel_id,
332                                    tags: tags.clone(),
333                                });
334                        }
335                    }
336                }
337                Element::Relation(_) | Element::Way(_) => {}
338            }
339
340            (local_nodes, local_map)
341        },
342        || (0_u64, HashMap::new()),
343        |(a_nodes, mut a_map), (b_nodes, b_map)| {
344            for (way_id, rels) in b_map {
345                a_map.entry(way_id).or_default().extend(rels);
346            }
347            (a_nodes + b_nodes, a_map)
348        },
349    )?;
350
351    if let Some(e) = write_error
352        .into_inner()
353        .unwrap_or_else(PoisonError::into_inner)
354    {
355        return Err(e);
356    }
357    sort_by_relation_id(&mut way_to_relations);
358    writer.finish()?;
359    store.flush()?;
360    store.prepare_for_reads()?;
361
362    let node_stats = NodeCollectionStats {
363        nodes_stored: total_stored,
364        max_node_id,
365    };
366
367    pb.finish_with_message(format!(
368        "done: {} nodes stored, {} ways with relation info",
369        node_stats.nodes_stored,
370        way_to_relations.len(),
371    ));
372
373    Ok(Pass1Result {
374        store,
375        node_stats,
376        way_to_relations,
377    })
378}
379
380/// Pass 1, or with `use_cache` the node store of an earlier run when its
381/// sidecar metadata still matches `source_pbf` (then only the relations are
382/// read again). A fresh pass 1 with `use_cache` writes that metadata, so
383/// the next run can skip the node scan: hours on a planet file.
384///
385/// Returns the result and whether the store came from the cache.
386///
387/// # Errors
388///
389/// When the PBF cannot be read or the node store cannot be created.
390pub fn pass1_or_cached(
391    pbf_path: &Path,
392    source_pbf: &Path,
393    store_path: &Path,
394    force_dense: bool,
395    use_cache: bool,
396    relations: Relations,
397) -> crate::error::Result<(Pass1Result, bool)> {
398    use crate::source::node_store::{NodeCacheMeta, try_open_cached, write_cache_meta};
399
400    if use_cache && let Some((store, meta)) = try_open_cached(store_path, source_pbf)? {
401        let way_to_relations = match relations {
402            Relations::Collect => preprocess_relations(pbf_path)?,
403            Relations::Skip => HashMap::new(),
404        };
405        let node_stats = NodeCollectionStats {
406            nodes_stored: meta.nodes_stored,
407            max_node_id: meta.max_node_id,
408        };
409        return Ok((
410            Pass1Result {
411                store,
412                node_stats,
413                way_to_relations,
414            },
415            true,
416        ));
417    }
418    let pass1 = pass1_nodes_and_relations(pbf_path, store_path, force_dense, relations)?;
419    if use_cache {
420        write_cache_meta(
421            store_path,
422            &NodeCacheMeta::for_build(
423                source_pbf,
424                pbf_path,
425                pass1.node_stats.max_node_id,
426                pass1.node_stats.nodes_stored,
427            )?,
428        )?;
429    }
430    Ok((pass1, false))
431}
432
433/// Put each way's relations in relation id order.
434///
435/// `par_map_reduce` merges blob results in whatever order the workers
436/// finish, so a way in relations from several blobs gets them in a
437/// different order on each run, and layers that read the first matching
438/// relation (a road's route `ref` and `network`, a boundary's tied admin
439/// level) would change between runs. Planetiler sorts the same way: its
440/// way-to-relation multimap returns each way's relations ordered by id
441/// (`LongLongMultimap.newAppendableMultimap(orderMask)`).
442fn sort_by_relation_id(way_to_relations: &mut HashMap<i64, Vec<CollectedRelation>>) {
443    for rels in way_to_relations.values_mut() {
444        rels.sort_by_key(|r| r.id);
445    }
446}
447
448/// Relation info collected during preprocessing.
449#[derive(Debug, Clone)]
450pub struct CollectedRelation {
451    /// Relation ID.
452    pub id: i64,
453    /// Tags on the relation.
454    pub tags: HashMap<String, String>,
455}
456
457/// Preprocess OSM relations to build a way→relation lookup table.
458///
459/// Scans the PBF file using parallel decompression (`par_map_reduce`)
460/// to find boundary and route relations. Returns a map from way ID
461/// to the relations that reference it.
462///
463/// # Errors
464///
465/// Returns an error if the PBF file can't be read.
466pub fn preprocess_relations(
467    pbf_path: &Path,
468) -> crate::error::Result<HashMap<i64, Vec<CollectedRelation>>> {
469    let pb = crate::progress::phase_spinner("OSM relations");
470    pb.set_message("preprocessing...");
471
472    let reader = ElementReader::from_path(pbf_path)?;
473    let elements_scanned = AtomicU64::new(0);
474    let mut way_to_relations: HashMap<i64, Vec<CollectedRelation>> = reader.par_map_reduce(
475        |element| {
476            let count = elements_scanned.fetch_add(1, Ordering::Relaxed) + 1;
477            if count.is_multiple_of(10_000_000) {
478                pb.set_message(format!("{count} elements scanned"));
479            }
480            let mut local_map: HashMap<i64, Vec<CollectedRelation>> = HashMap::new();
481            if let Element::Relation(rel) = element {
482                let tags: HashMap<String, String> = rel
483                    .tags()
484                    .map(|(k, v)| (k.to_string(), v.to_string()))
485                    .collect();
486
487                let is_boundary = tags.get("type").is_some_and(|t| t == "boundary")
488                    || tags.contains_key("boundary");
489                let is_route = tags.get("type").is_some_and(|t| t == "route");
490
491                if is_boundary || is_route {
492                    let rel_id = rel.id();
493
494                    let way_member_ids: Vec<i64> = rel
495                        .members()
496                        .filter(|m| m.member_type == osmpbf::elements::RelMemberType::Way)
497                        .map(|m| m.member_id)
498                        .collect();
499
500                    for way_id in &way_member_ids {
501                        local_map
502                            .entry(*way_id)
503                            .or_default()
504                            .push(CollectedRelation {
505                                id: rel_id,
506                                tags: tags.clone(),
507                            });
508                    }
509                }
510            }
511            local_map
512        },
513        HashMap::new,
514        |mut a, b| {
515            for (way_id, rels) in b {
516                a.entry(way_id).or_default().extend(rels);
517            }
518            a
519        },
520    )?;
521
522    sort_by_relation_id(&mut way_to_relations);
523
524    pb.finish_with_message(format!(
525        "done: {} ways with relation info",
526        way_to_relations.len(),
527    ));
528
529    Ok(way_to_relations)
530}
531
532/// Convert a single OSM element to an [`InputFeature`], if applicable.
533///
534/// Nodes with empty tags are skipped. Ways with fewer than 2 resolved
535/// coordinates are skipped. Relations are skipped (multipolygon assembly
536/// not yet implemented).
537///
538/// This function is designed for parallel invocation — it takes only
539/// shared references to the node store and relation map.
540pub fn element_to_feature(
541    element: Element<'_>,
542    store: &NodeStore,
543    way_to_relations: &HashMap<i64, Vec<CollectedRelation>>,
544    suppress_india_boundaries: bool,
545) -> Option<InputFeature> {
546    match element {
547        Element::DenseNode(node) => {
548            let tags: HashMap<String, String> = node
549                .tags()
550                .map(|(k, v)| (k.to_string(), v.to_string()))
551                .collect();
552
553            if tags.is_empty() {
554                return None;
555            }
556
557            let properties = tags_to_properties(&tags);
558            Some(InputFeature {
559                id: node.id as u64,
560                geometry: Arc::new(geo::Geometry::Point(geo::Point::new(
561                    node.lon(),
562                    node.lat(),
563                ))),
564                properties,
565                bbox: None,
566                source: DataSource::Osm {
567                    element_type: OsmElementType::Node,
568                    relations: Vec::new(),
569                },
570            })
571        }
572        Element::Node(node) => {
573            let tags: HashMap<String, String> = node
574                .tags()
575                .map(|(k, v)| (k.to_string(), v.to_string()))
576                .collect();
577
578            if tags.is_empty() {
579                return None;
580            }
581
582            let properties = tags_to_properties(&tags);
583            Some(InputFeature {
584                id: node.id() as u64,
585                geometry: Arc::new(geo::Geometry::Point(geo::Point::new(
586                    node.lon(),
587                    node.lat(),
588                ))),
589                properties,
590                bbox: None,
591                source: DataSource::Osm {
592                    element_type: OsmElementType::Node,
593                    relations: Vec::new(),
594                },
595            })
596        }
597        Element::Way(way) => {
598            let tags: HashMap<String, String> = way
599                .tags()
600                .map(|(k, v)| (k.to_string(), v.to_string()))
601                .collect();
602
603            if tags.is_empty() {
604                return None;
605            }
606
607            let refs: Vec<i64> = way.refs().collect();
608            let coords: Vec<geo::Coord<f64>> = refs
609                .iter()
610                .filter_map(|node_id| {
611                    store
612                        .get(*node_id as u64)
613                        .map(|(lat, lon)| geo::Coord { x: lon, y: lat })
614                })
615                .collect();
616
617            if coords.len() < 2 {
618                return None;
619            }
620
621            let relations = build_relation_info(way.id(), way_to_relations);
622
623            if suppress_india_boundaries
624                && should_suppress_india_boundary(&tags, &relations, &coords)
625            {
626                return None;
627            }
628
629            let is_closed = coords.len() >= 4 && coords.first() == coords.last();
630            let is_area = is_closed && is_area_tag(&tags);
631
632            let geometry = if is_area {
633                let ring = geo::LineString::new(coords);
634                geo::Geometry::Polygon(geo::Polygon::new(ring, vec![]))
635            } else {
636                geo::Geometry::LineString(geo::LineString::new(coords))
637            };
638
639            let properties = tags_to_properties(&tags);
640            Some(InputFeature {
641                id: way.id() as u64,
642                geometry: Arc::new(geometry),
643                properties,
644                bbox: None,
645                source: DataSource::Osm {
646                    element_type: OsmElementType::Way,
647                    relations,
648                },
649            })
650        }
651        Element::Relation(_) => {
652            // Multipolygon relation assembly requires storing
653            // way geometries (a third pass). Skipped for now.
654            None
655        }
656    }
657}
658
659/// Check if an OSM `admin_level=2` boundary should be suppressed in India extent.
660fn should_suppress_india_boundary(
661    tags: &HashMap<String, String>,
662    relations: &[RelationInfo],
663    coords: &[geo::Coord<f64>],
664) -> bool {
665    // Check if this way is part of an admin_level=2 boundary relation
666    let is_admin2_boundary = relations.iter().any(|rel| {
667        rel.admin_level == Some(2)
668            && rel
669                .tags
670                .get("boundary")
671                .is_some_and(|b| b == "administrative")
672    });
673
674    // Also check if the way itself has boundary=administrative + admin_level=2
675    let way_is_admin2 = tags.get("boundary").is_some_and(|b| b == "administrative")
676        && tags.get("admin_level").is_some_and(|l| l == "2");
677
678    if !is_admin2_boundary && !way_is_admin2 {
679        return false;
680    }
681
682    // Check if any coordinate falls within India bbox
683    coords.iter().any(|c| {
684        c.x >= INDIA_BBOX[0] && c.x <= INDIA_BBOX[2] && c.y >= INDIA_BBOX[1] && c.y <= INDIA_BBOX[3]
685    })
686}
687
688/// Build relation info for an OSM way.
689fn build_relation_info(
690    way_id: i64,
691    way_to_relations: &HashMap<i64, Vec<CollectedRelation>>,
692) -> Vec<RelationInfo> {
693    let Some(rels) = way_to_relations.get(&way_id) else {
694        return Vec::new();
695    };
696
697    rels.iter()
698        .map(|rel| {
699            let admin_level = rel
700                .tags
701                .get("admin_level")
702                .and_then(|v| v.parse::<i32>().ok());
703
704            let disputed = rel.tags.get("boundary").is_some_and(|b| b == "disputed")
705                || rel.tags.get("disputed").is_some_and(|d| d == "yes")
706                || rel.tags.contains_key("disputed_by")
707                || rel.tags.contains_key("claimed_by");
708
709            RelationInfo {
710                id: rel.id,
711                admin_level,
712                disputed,
713                role: String::new(),
714                tags: rel.tags.clone(),
715            }
716        })
717        .collect()
718}
719
720/// Convert OSM tags to property map.
721pub fn tags_to_properties(tags: &HashMap<String, String>) -> HashMap<String, PropValue> {
722    let mut props = HashMap::with_capacity(tags.len());
723    for (key, value) in tags {
724        // Try to parse numeric values
725        if let Ok(n) = value.parse::<i64>() {
726            props.insert(key.clone(), PropValue::I64(n));
727        } else if let Ok(f) = value.parse::<f64>() {
728            props.insert(key.clone(), PropValue::F64(f));
729        } else {
730            props.insert(key.clone(), PropValue::Str(value.clone()));
731        }
732    }
733    props
734}
735
736/// Check if OSM tags indicate an area feature (closed way = polygon).
737fn is_area_tag(tags: &HashMap<String, String>) -> bool {
738    // Explicit area=yes
739    if tags.get("area").is_some_and(|v| v == "yes") {
740        return true;
741    }
742
743    // Tags that imply area
744    let area_keys = [
745        "building",
746        "building:part",
747        "landuse",
748        "natural",
749        "leisure",
750        "amenity",
751        "shop",
752        "tourism",
753        "place",
754        "aeroway",
755        "waterway",
756    ];
757
758    for key in &area_keys {
759        if let Some(val) = tags.get(*key) {
760            // waterway=* is only an area for certain values
761            if *key == "waterway" {
762                return matches!(
763                    val.as_str(),
764                    "riverbank" | "dock" | "dam" | "boatyard" | "fuel"
765                );
766            }
767            // natural=coastline is a line, not area
768            if *key == "natural" && val == "coastline" {
769                return false;
770            }
771            return true;
772        }
773    }
774
775    false
776}
777
778#[cfg(test)]
779mod tests {
780    use super::*;
781
782    #[test]
783    fn the_first_failed_node_write_is_kept() {
784        use crate::error::GeolithError;
785        let slot = Mutex::new(None);
786        record_write(&slot, Ok(()));
787        assert!(slot.lock().unwrap().is_none());
788        record_write(&slot, Err(GeolithError::NodeStore("first".into())));
789        record_write(&slot, Err(GeolithError::NodeStore("second".into())));
790        let kept = slot.into_inner().unwrap().expect("an error was kept");
791        assert_eq!(kept.to_string(), "node store error: first");
792    }
793
794    /// A negative id (an unsaved JOSM edit) has no slot in a dense store:
795    /// pass 1 must fail, not write outside the mapped file.
796    #[test]
797    fn a_negative_node_id_fails_pass_1() {
798        let pbf =
799            Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/negative-node-ids.osm.pbf");
800        let tmp = tempfile::tempdir().expect("tmp");
801        let result = pass1_nodes_and_relations(
802            &pbf,
803            &tmp.path().join("nodes.bin"),
804            true,
805            Relations::Collect,
806        );
807        let Err(e) = result else {
808            panic!("a negative node id must fail pass 1");
809        };
810        assert!(
811            e.to_string().contains("exceeds the store capacity 7"),
812            "{e}"
813        );
814    }
815
816    fn fixture(name: &str) -> std::path::PathBuf {
817        Path::new(env!("CARGO_MANIFEST_DIR"))
818            .join("tests/fixtures")
819            .join(name)
820    }
821
822    /// The expected values are osmium's own `fileinfo -e` "Largest node ID"
823    /// for each fixture, and the full scan must agree. The sorted fixtures
824    /// hold 20,000 nodes, which osmium writes as three node blobs, so the
825    /// bisection has more than one blob to search.
826    #[test]
827    fn sorted_pbfs_give_the_max_node_id_from_the_last_node_blob() {
828        for (name, expected) in [
829            ("sorted-many-blobs.osm.pbf", 140_993),
830            ("sorted-nodes-only.osm.pbf", 140_993),
831            ("sorted-no-nodes.osm.pbf", 0),
832        ] {
833            let pbf = fixture(name);
834            assert_eq!(
835                sorted_max_node_id(&pbf).expect("read"),
836                Some(expected),
837                "{name}"
838            );
839            assert_eq!(
840                full_scan_max_node_id(&pbf).expect("scan"),
841                expected,
842                "{name}"
843            );
844        }
845    }
846
847    /// Without the header flag the order is not trusted, and the full scan
848    /// answers.
849    #[test]
850    fn pbfs_without_the_sort_flag_fall_back_to_a_full_scan() {
851        for (name, expected) in [
852            ("boundaries.osm.pbf", 300),
853            ("relations.osm.pbf", 3),
854            ("high-node-ids.osm.pbf", 14_000_000_001),
855        ] {
856            let pbf = fixture(name);
857            assert_eq!(sorted_max_node_id(&pbf).expect("read"), None, "{name}");
858            assert_eq!(scan_max_node_id(&pbf).expect("scan"), expected, "{name}");
859        }
860    }
861
862    /// Protobuf wire-format encoding of the PBF messages these tests build,
863    /// written from `osmformat.proto` and `fileformat.proto` so the reader is
864    /// checked against the spec rather than against osmpbf's own writer.
865    mod pbf {
866        fn varint(mut v: u64, out: &mut Vec<u8>) {
867            while v >= 0x80 {
868                out.push((v as u8) | 0x80);
869                v >>= 7;
870            }
871            out.push(v as u8);
872        }
873
874        fn uint(field: u64, v: u64, out: &mut Vec<u8>) {
875            varint(field << 3, out);
876            varint(v, out);
877        }
878
879        fn sint(field: u64, v: i64, out: &mut Vec<u8>) {
880            uint(field, ((v << 1) ^ (v >> 63)) as u64, out);
881        }
882
883        fn bytes(field: u64, b: &[u8], out: &mut Vec<u8>) {
884            varint((field << 3) | 2, out);
885            varint(b.len() as u64, out);
886            out.extend_from_slice(b);
887        }
888
889        /// A `HeaderBlock` with the given optional features.
890        pub fn header_block(optional: &[&str]) -> Vec<u8> {
891            let mut out = Vec::new();
892            bytes(4, b"OsmSchema-V0.6", &mut out);
893            for f in optional {
894                bytes(5, f.as_bytes(), &mut out);
895            }
896            out
897        }
898
899        /// A `PrimitiveBlock` of plain (non-dense) nodes, one group.
900        pub fn node_block(ids: &[i64]) -> Vec<u8> {
901            let mut group = Vec::new();
902            for &id in ids {
903                let mut node = Vec::new();
904                sint(1, id, &mut node);
905                sint(8, 0, &mut node);
906                sint(9, 0, &mut node);
907                bytes(1, &node, &mut group);
908            }
909            block(&group)
910        }
911
912        /// A `PrimitiveBlock` holding one way and no node.
913        pub fn way_block(id: i64) -> Vec<u8> {
914            let mut way = Vec::new();
915            uint(1, id as u64, &mut way);
916            let mut group = Vec::new();
917            bytes(3, &way, &mut group);
918            block(&group)
919        }
920
921        fn block(group: &[u8]) -> Vec<u8> {
922            let mut table = Vec::new();
923            bytes(1, b"", &mut table);
924            let mut out = Vec::new();
925            bytes(1, &table, &mut out);
926            bytes(2, group, &mut out);
927            out
928        }
929
930        /// One file block: the 4-byte big-endian `BlobHeader` length, the
931        /// `BlobHeader`, then a `Blob` holding `data` uncompressed.
932        pub fn file_block(blob_type: &str, data: &[u8]) -> Vec<u8> {
933            let mut blob = Vec::new();
934            bytes(1, data, &mut blob);
935            uint(2, data.len() as u64, &mut blob);
936            let mut header = Vec::new();
937            bytes(1, blob_type.as_bytes(), &mut header);
938            uint(3, blob.len() as u64, &mut header);
939            let mut out = (header.len() as u32).to_be_bytes().to_vec();
940            out.extend_from_slice(&header);
941            out.extend_from_slice(&blob);
942            out
943        }
944    }
945
946    fn write_pbf(dir: &tempfile::TempDir, name: &str, blocks: &[Vec<u8>]) -> std::path::PathBuf {
947        let path = dir.path().join(name);
948        std::fs::write(&path, blocks.concat()).expect("write pbf");
949        path
950    }
951
952    fn sorted_header() -> Vec<u8> {
953        pbf::file_block("OSMHeader", &pbf::header_block(&[SORTED_FEATURE]))
954    }
955
956    /// Plain nodes count like dense ones, the way blobs after the node blobs
957    /// are past the bisection's end, and a blob type the spec does not define
958    /// is skipped: the answer is 99, the largest id written.
959    #[test]
960    fn sorted_pbf_of_plain_nodes_gives_the_largest_written_id() {
961        let dir = tempfile::tempdir().expect("tempdir");
962        let path = write_pbf(
963            &dir,
964            "plain.osm.pbf",
965            &[
966                sorted_header(),
967                pbf::file_block("OSMData", &pbf::node_block(&[5, 42, 17])),
968                pbf::file_block("OSMData", &pbf::node_block(&[61, 99])),
969                pbf::file_block("OSMFuture", b"opaque"),
970                pbf::file_block("OSMData", &pbf::way_block(7)),
971                pbf::file_block("OSMData", &pbf::way_block(8)),
972            ],
973        );
974        assert_eq!(sorted_max_node_id(&path).expect("read"), Some(99));
975        assert_eq!(full_scan_max_node_id(&path).expect("scan"), 99);
976    }
977
978    /// A file with no `OSMHeader` blob carries no sort flag to trust.
979    #[test]
980    fn pbf_without_a_header_blob_is_not_trusted_as_sorted() {
981        let dir = tempfile::tempdir().expect("tempdir");
982        let path = write_pbf(
983            &dir,
984            "headless.osm.pbf",
985            &[pbf::file_block("OSMData", &pbf::node_block(&[3]))],
986        );
987        assert_eq!(sorted_max_node_id(&path).expect("read"), None);
988    }
989
990    /// The sanity cap applies to the sorted path too: an id one past
991    /// 2^40 is rejected, not used to size a 8 TiB store.
992    #[test]
993    fn sorted_pbf_with_an_id_above_the_cap_is_an_error() {
994        let dir = tempfile::tempdir().expect("tempdir");
995        let path = write_pbf(
996            &dir,
997            "huge.osm.pbf",
998            &[
999                sorted_header(),
1000                pbf::file_block("OSMData", &pbf::node_block(&[(1 << 40) + 1])),
1001            ],
1002        );
1003        let e = scan_max_node_id(&path).expect_err("an id above 2^40 must be rejected");
1004        assert!(e.to_string().contains("is above 1099511627776"), "{e}");
1005    }
1006
1007    /// A missing file, a truncated blob header, a blob cut short of its
1008    /// declared size, a header blob that is not a `HeaderBlock` and a node
1009    /// blob that is not a `PrimitiveBlock` are all errors rather than a
1010    /// silent 0. An unsorted file with a bad blob is not decoded by the
1011    /// sorted path at all, so the full scan is the one that reports it.
1012    #[test]
1013    fn unreadable_pbfs_are_errors() {
1014        let dir = tempfile::tempdir().expect("tempdir");
1015        // Field 1 with wire type 7, which protobuf does not define.
1016        let garbage = [0x0f];
1017        let cut = |mut block: Vec<u8>| {
1018            block.truncate(block.len() - 3);
1019            block
1020        };
1021        let unsorted = pbf::file_block("OSMHeader", &pbf::header_block(&[]));
1022        let cases = [
1023            ("truncated", true, vec![vec![0, 0, 0, 40, 0x0a]]),
1024            (
1025                "bad-header",
1026                true,
1027                vec![pbf::file_block("OSMHeader", &garbage)],
1028            ),
1029            ("short-header", true, vec![cut(sorted_header())]),
1030            (
1031                "bad-data",
1032                true,
1033                vec![sorted_header(), pbf::file_block("OSMData", &garbage)],
1034            ),
1035            (
1036                "short-data",
1037                true,
1038                vec![
1039                    sorted_header(),
1040                    cut(pbf::file_block("OSMData", &pbf::node_block(&[1, 2]))),
1041                ],
1042            ),
1043            (
1044                "unsorted-bad-data",
1045                false,
1046                vec![unsorted, pbf::file_block("OSMData", &garbage)],
1047            ),
1048        ];
1049        for (name, sorted_errs, blocks) in cases {
1050            let path = write_pbf(&dir, name, &blocks);
1051            let sorted = sorted_max_node_id(&path);
1052            if sorted_errs {
1053                assert!(sorted.is_err(), "{name}: {sorted:?}");
1054            } else {
1055                assert_eq!(sorted.expect("read"), None, "{name}");
1056            }
1057            assert!(scan_max_node_id(&path).is_err(), "{name}");
1058        }
1059        assert!(scan_max_node_id(&dir.path().join("missing.osm.pbf")).is_err());
1060    }
1061
1062    /// OSM node ids passed 13 billion in 2026; a node above that must keep
1063    /// its coordinates, or every way through it loses a point.
1064    #[test]
1065    fn a_node_above_13_billion_keeps_its_coordinates() {
1066        let pbf =
1067            Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/high-node-ids.osm.pbf");
1068        assert_eq!(scan_max_node_id(&pbf).expect("scan"), 14_000_000_001);
1069        for force_dense in [true, false] {
1070            let tmp = tempfile::tempdir().expect("tmp");
1071            let pass1 = pass1_nodes_and_relations(
1072                &pbf,
1073                &tmp.path().join("nodes.bin"),
1074                force_dense,
1075                Relations::Collect,
1076            )
1077            .expect("pass 1");
1078            let (lat, lon) = pass1
1079                .store
1080                .get(14_000_000_001)
1081                .expect("the high node is stored");
1082            assert!(
1083                (lat - 37.795).abs() < 1e-6 && (lon + 122.41).abs() < 1e-6,
1084                "{lat} {lon}"
1085            );
1086        }
1087    }
1088
1089    #[test]
1090    fn tags_to_properties_parses_types() {
1091        let mut tags = HashMap::new();
1092        tags.insert("name".to_string(), "Main Street".to_string());
1093        tags.insert("lanes".to_string(), "2".to_string());
1094        tags.insert("maxspeed".to_string(), "50.5".to_string());
1095
1096        let props = tags_to_properties(&tags);
1097        assert_eq!(
1098            props.get("name"),
1099            Some(&PropValue::Str("Main Street".to_string()))
1100        );
1101        assert_eq!(props.get("lanes"), Some(&PropValue::I64(2)));
1102        assert_eq!(props.get("maxspeed"), Some(&PropValue::F64(50.5)));
1103    }
1104
1105    #[test]
1106    fn is_area_building() {
1107        let mut tags = HashMap::new();
1108        tags.insert("building".to_string(), "yes".to_string());
1109        assert!(is_area_tag(&tags));
1110    }
1111
1112    #[test]
1113    fn is_area_explicit() {
1114        let mut tags = HashMap::new();
1115        tags.insert("area".to_string(), "yes".to_string());
1116        assert!(is_area_tag(&tags));
1117    }
1118
1119    #[test]
1120    fn is_not_area_highway() {
1121        let mut tags = HashMap::new();
1122        tags.insert("highway".to_string(), "residential".to_string());
1123        assert!(!is_area_tag(&tags));
1124    }
1125
1126    #[test]
1127    fn is_not_area_coastline() {
1128        let mut tags = HashMap::new();
1129        tags.insert("natural".to_string(), "coastline".to_string());
1130        assert!(!is_area_tag(&tags));
1131    }
1132
1133    #[test]
1134    fn waterway_area_selective() {
1135        let mut tags = HashMap::new();
1136        tags.insert("waterway".to_string(), "riverbank".to_string());
1137        assert!(is_area_tag(&tags));
1138
1139        let mut tags2 = HashMap::new();
1140        tags2.insert("waterway".to_string(), "river".to_string());
1141        assert!(!is_area_tag(&tags2));
1142    }
1143
1144    #[test]
1145    fn india_boundary_suppression() {
1146        let tags = HashMap::new();
1147        let relations = vec![RelationInfo {
1148            id: 1,
1149            admin_level: Some(2),
1150            disputed: false,
1151            role: String::new(),
1152            tags: {
1153                let mut t = HashMap::new();
1154                t.insert("boundary".to_string(), "administrative".to_string());
1155                t
1156            },
1157        }];
1158
1159        // Coordinates inside India
1160        let coords_india = vec![geo::Coord { x: 77.0, y: 28.0 }];
1161        assert!(should_suppress_india_boundary(
1162            &tags,
1163            &relations,
1164            &coords_india
1165        ));
1166
1167        // Coordinates outside India
1168        let coords_outside = vec![geo::Coord { x: 10.0, y: 50.0 }];
1169        assert!(!should_suppress_india_boundary(
1170            &tags,
1171            &relations,
1172            &coords_outside
1173        ));
1174    }
1175
1176    #[test]
1177    fn india_boundary_not_suppressed_for_non_admin2() {
1178        let tags = HashMap::new();
1179        let relations = vec![RelationInfo {
1180            id: 1,
1181            admin_level: Some(4),
1182            disputed: false,
1183            role: String::new(),
1184            tags: {
1185                let mut t = HashMap::new();
1186                t.insert("boundary".to_string(), "administrative".to_string());
1187                t
1188            },
1189        }];
1190
1191        let coords = vec![geo::Coord { x: 77.0, y: 28.0 }];
1192        assert!(!should_suppress_india_boundary(&tags, &relations, &coords));
1193    }
1194
1195    #[test]
1196    fn build_relation_info_empty() {
1197        let map: HashMap<i64, Vec<CollectedRelation>> = HashMap::new();
1198        let info = build_relation_info(42, &map);
1199        assert!(info.is_empty());
1200    }
1201
1202    #[test]
1203    fn build_relation_info_with_admin() {
1204        let mut map: HashMap<i64, Vec<CollectedRelation>> = HashMap::new();
1205        let mut tags = HashMap::new();
1206        tags.insert("admin_level".to_string(), "2".to_string());
1207        tags.insert("boundary".to_string(), "administrative".to_string());
1208
1209        map.insert(42, vec![CollectedRelation { id: 100, tags }]);
1210
1211        let info = build_relation_info(42, &map);
1212        assert_eq!(info.len(), 1);
1213        assert_eq!(info[0].id, 100);
1214        assert_eq!(info[0].admin_level, Some(2));
1215        assert!(!info[0].disputed);
1216    }
1217
1218    #[test]
1219    fn build_relation_info_disputed() {
1220        let mut map: HashMap<i64, Vec<CollectedRelation>> = HashMap::new();
1221        let mut tags = HashMap::new();
1222        tags.insert("boundary".to_string(), "disputed".to_string());
1223
1224        map.insert(42, vec![CollectedRelation { id: 200, tags }]);
1225
1226        let info = build_relation_info(42, &map);
1227        assert_eq!(info.len(), 1);
1228        assert!(info[0].disputed);
1229    }
1230
1231    /// `tests/fixtures/relations.osm`: bus route 100 has ways 10 and 11;
1232    /// boundary 200 has way 11.
1233    fn relations_fixture() -> std::path::PathBuf {
1234        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relations.osm.pbf")
1235    }
1236
1237    /// Relation ids per way, sorted, so the parallel scan order is irrelevant.
1238    fn relation_ids(map: &HashMap<i64, Vec<CollectedRelation>>) -> Vec<(i64, Vec<i64>)> {
1239        let mut ids: Vec<(i64, Vec<i64>)> = map
1240            .iter()
1241            .map(|(way, rels)| {
1242                let mut rel_ids: Vec<i64> = rels.iter().map(|r| r.id).collect();
1243                rel_ids.sort_unstable();
1244                (*way, rel_ids)
1245            })
1246            .collect();
1247        ids.sort_unstable();
1248        ids
1249    }
1250
1251    /// `route-relations-many-blobs.osm.pbf`: motorway ways 10 and 11 belong
1252    /// to road routes 1, 10001 and 20001, with 9,999 `type=site` relations
1253    /// (one node member each) between each, so osmium writes the three routes into
1254    /// different blobs and a parallel scan reads them in any order.
1255    const MANY_BLOB_ROUTES: [i64; 3] = [1, 10_001, 20_001];
1256
1257    /// The relations of each way in their stored order, unsorted.
1258    fn stored_relation_ids(map: &HashMap<i64, Vec<CollectedRelation>>, way: i64) -> Vec<i64> {
1259        map.get(&way)
1260            .map(|rels| rels.iter().map(|r| r.id).collect())
1261            .unwrap_or_default()
1262    }
1263
1264    /// A way's relations are in relation id order whatever the thread count
1265    /// and blob scheduling, as Planetiler stores them (its way-to-relation
1266    /// multimap sorts each way's values), so the first route a layer reads
1267    /// is always the same one.
1268    #[test]
1269    fn a_ways_relations_come_in_id_order_on_any_thread_count() {
1270        let pbf = Path::new(env!("CARGO_MANIFEST_DIR"))
1271            .join("tests/fixtures/route-relations-many-blobs.osm.pbf");
1272        let tmp = tempfile::tempdir().expect("tmp");
1273        for (run, threads) in [1, 8, 4, 8, 2, 8, 4, 8].into_iter().enumerate() {
1274            let pool = rayon::ThreadPoolBuilder::new()
1275                .num_threads(threads)
1276                .build()
1277                .expect("thread pool");
1278            let preprocessed = pool.install(|| preprocess_relations(&pbf)).expect("scan");
1279            let pass1 = pool
1280                .install(|| {
1281                    pass1_nodes_and_relations(
1282                        &pbf,
1283                        &tmp.path().join(format!("nodes-{run}.bin")),
1284                        true,
1285                        Relations::Collect,
1286                    )
1287                })
1288                .expect("pass 1");
1289            for way in [10, 11] {
1290                assert_eq!(
1291                    stored_relation_ids(&preprocessed, way),
1292                    MANY_BLOB_ROUTES,
1293                    "preprocess, run {run} on {threads} threads, way {way}"
1294                );
1295                assert_eq!(
1296                    stored_relation_ids(&pass1.way_to_relations, way),
1297                    MANY_BLOB_ROUTES,
1298                    "pass 1, run {run} on {threads} threads, way {way}"
1299                );
1300            }
1301        }
1302    }
1303
1304    /// Node 2 of the fixture: lat 18.53, lon 73.86.
1305    fn assert_node_2(store: &NodeStore) {
1306        let (lat, lon) = store.get(2).expect("node 2 is stored");
1307        assert!(
1308            (lat - 18.53).abs() < 1e-6 && (lon - 73.86).abs() < 1e-6,
1309            "{lat} {lon}"
1310        );
1311    }
1312
1313    #[test]
1314    fn pass1_collects_relations_for_tiles_and_skips_them_for_geocoding() {
1315        let tmp = tempfile::tempdir().expect("tmp");
1316        let collect = pass1_nodes_and_relations(
1317            &relations_fixture(),
1318            &tmp.path().join("collect.bin"),
1319            true,
1320            Relations::Collect,
1321        )
1322        .expect("pass 1");
1323        assert_eq!(
1324            relation_ids(&collect.way_to_relations),
1325            vec![(10, vec![100]), (11, vec![100, 200])]
1326        );
1327        assert_node_2(&collect.store);
1328
1329        let skip = pass1_nodes_and_relations(
1330            &relations_fixture(),
1331            &tmp.path().join("skip.bin"),
1332            true,
1333            Relations::Skip,
1334        )
1335        .expect("pass 1");
1336        assert!(skip.way_to_relations.is_empty(), "relations collected");
1337        assert_eq!(skip.node_stats.nodes_stored, 3);
1338        assert_node_2(&skip.store);
1339    }
1340
1341    #[test]
1342    fn a_cached_node_store_reads_relations_only_when_asked() {
1343        let tmp = tempfile::tempdir().expect("tmp");
1344        let pbf = relations_fixture();
1345        let store = tmp.path().join("nodes.bin");
1346        let (first, cached) =
1347            pass1_or_cached(&pbf, &pbf, &store, true, true, Relations::Skip).expect("pass 1");
1348        assert!(!cached, "the first run scans the nodes");
1349        drop(first);
1350
1351        let (skip, cached) =
1352            pass1_or_cached(&pbf, &pbf, &store, true, true, Relations::Skip).expect("cache");
1353        assert!(cached, "the second run reuses the store");
1354        assert!(skip.way_to_relations.is_empty(), "relations read again");
1355        assert_node_2(&skip.store);
1356        drop(skip);
1357
1358        let (collect, cached) =
1359            pass1_or_cached(&pbf, &pbf, &store, true, true, Relations::Collect).expect("cache");
1360        assert!(cached);
1361        assert_eq!(
1362            relation_ids(&collect.way_to_relations),
1363            vec![(10, vec![100]), (11, vec![100, 200])]
1364        );
1365    }
1366
1367    #[test]
1368    fn a_cached_node_store_fails_when_its_relations_cannot_be_read() {
1369        let tmp = tempfile::tempdir().expect("tmp");
1370        let pbf = relations_fixture();
1371        let store = tmp.path().join("nodes.bin");
1372        let (first, _) =
1373            pass1_or_cached(&pbf, &pbf, &store, true, true, Relations::Skip).expect("pass 1");
1374        drop(first);
1375
1376        // The cache matches the source PBF, so the nodes need no read of the
1377        // missing PBF; the relations do.
1378        let missing = tmp.path().join("missing.osm.pbf");
1379        let (skip, cached) = pass1_or_cached(&missing, &pbf, &store, true, true, Relations::Skip)
1380            .expect("the cache needs no PBF");
1381        assert!(cached);
1382        drop(skip);
1383        let collect = pass1_or_cached(&missing, &pbf, &store, true, true, Relations::Collect);
1384        assert!(
1385            collect.is_err(),
1386            "relations of a missing PBF cannot be read"
1387        );
1388    }
1389
1390    /// A store built from an extract holds the nodes of one box. The sidecar
1391    /// recorded only the source PBF, so a later run on the whole file took
1392    /// the store and lost every way with a node outside the box.
1393    #[test]
1394    fn a_store_built_from_an_extract_is_not_reused_for_the_whole_pbf() {
1395        let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
1396        let source = fixtures.join("relations.osm.pbf");
1397        // Any other valid PBF stands for the extract osmium cut from `source`.
1398        let extract = fixtures.join("route-relations-many-blobs.osm.pbf");
1399        let dir = tempfile::tempdir().expect("tmp");
1400        let store = dir.path().join("nodes.bin");
1401        let build = |scanned: &Path| {
1402            pass1_or_cached(scanned, &source, &store, true, true, Relations::Skip)
1403                .expect("pass 1")
1404                .1
1405        };
1406        assert!(!build(&extract), "the first run builds the store");
1407        assert!(
1408            !build(&source),
1409            "the store of an extract is not the store of the whole PBF"
1410        );
1411        assert!(build(&source), "a store of the whole PBF is reused");
1412    }
1413
1414    /// A zero-byte or truncated-to-nothing file (a failed download) used to read
1415    /// as a PBF with no nodes: the build went on with an empty planet.
1416    #[test]
1417    fn a_file_that_is_not_an_osm_pbf_is_an_error_that_names_it() {
1418        let dir = tempfile::tempdir().expect("tmp");
1419        for (name, bytes) in [("empty.pbf", &b""[..]), ("three.pbf", &b"x\n\n"[..])] {
1420            let path = dir.path().join(name);
1421            std::fs::write(&path, bytes).expect("write");
1422            let err = scan_max_node_id(&path).expect_err(name);
1423            let text = crate::error::report(&err);
1424            assert!(text.contains(name), "{text}");
1425            assert!(text.contains("not an OSM PBF"), "{text}");
1426        }
1427        let fixture =
1428            Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relations.osm.pbf");
1429        if fixture.exists() {
1430            scan_max_node_id(&fixture).expect("a real PBF is accepted");
1431        }
1432    }
1433}