Skip to main content

geolith/source/
osmium.rs

1//! Optional osmium-tool integration for bbox-based PBF extraction.
2//!
3//! When `--bbox` is passed and `osmium` is on `$PATH`, this module runs
4//! `osmium extract` to crop the planet PBF to just the target region.
5//! A cropped PBF is dramatically smaller (planet → regional extract),
6//! making both node collection and feature processing much faster.
7//!
8//! If `osmium` is not installed, the pipeline falls back gracefully to
9//! processing the full PBF with in-memory bbox filtering.
10
11use std::path::{Path, PathBuf};
12use std::process::Command;
13
14use crate::source::bbox_filter::Bbox;
15
16/// Result of an osmium extract attempt.
17#[derive(Debug)]
18pub struct ExtractResult {
19    /// Path to the PBF file to use (extracted or original).
20    pub pbf_path: PathBuf,
21    /// Whether an extracted file was created (needs cleanup).
22    pub is_extracted: bool,
23}
24
25/// Check if osmium CLI is available on `$PATH`.
26#[must_use]
27fn osmium_available(program: &str) -> bool {
28    Command::new(program)
29        .arg("--version")
30        .stdout(std::process::Stdio::null())
31        .stderr(std::process::Stdio::null())
32        .status()
33        .is_ok()
34}
35
36/// Try to extract a bbox region from a PBF file using osmium.
37///
38/// If osmium is installed and extraction succeeds, returns the path to
39/// the extracted (smaller) PBF file. If osmium is not installed, returns the
40/// original path.
41///
42/// The extracted file is placed in `output_dir` as `geolith-extract.osm.pbf`.
43///
44/// # Errors
45///
46/// Returns an error if osmium is found but extraction fails (corrupt PBF,
47/// disk full): going on with the full PBF would run a build meant for a
48/// small box over the whole file. Missing osmium is NOT an error: the
49/// function falls back to the full PBF, which is filtered by box.
50pub fn try_extract(
51    pbf_path: &Path,
52    bbox: &Bbox,
53    output_dir: &Path,
54) -> crate::error::Result<ExtractResult> {
55    try_extract_with("osmium", pbf_path, bbox, output_dir)
56}
57
58/// [`try_extract`] with the name of the `osmium` program to run.
59///
60/// # Errors
61///
62/// As [`try_extract`].
63pub fn try_extract_with(
64    program: &str,
65    pbf_path: &Path,
66    bbox: &Bbox,
67    output_dir: &Path,
68) -> crate::error::Result<ExtractResult> {
69    if !osmium_available(program) {
70        tracing::info!(
71            "osmium not found on $PATH — processing full PBF \"{}\"",
72            pbf_path.display(),
73        );
74        return Ok(ExtractResult {
75            pbf_path: pbf_path.to_path_buf(),
76            is_extracted: false,
77        });
78    }
79
80    let extract_path = output_dir.join("geolith-extract.osm.pbf");
81    let bbox_str = format!(
82        "{},{},{},{}",
83        bbox.min_lon, bbox.min_lat, bbox.max_lon, bbox.max_lat,
84    );
85
86    tracing::info!(
87        "osmium extract --bbox {} {} → {}",
88        bbox_str,
89        pbf_path.display(),
90        extract_path.display(),
91    );
92
93    let status = Command::new(program)
94        .args([
95            "extract",
96            "--bbox",
97            &bbox_str,
98            "--overwrite",
99            "--set-bounds",
100            "--strategy",
101            "smart",
102        ])
103        .arg(pbf_path)
104        .arg("-o")
105        .arg(&extract_path)
106        .status()?;
107
108    if !status.success() {
109        // Clean up partial output if it exists. A failed removal changes
110        // nothing: the build stops here, and the next extract overwrites the
111        // file (`--overwrite`).
112        let _ = std::fs::remove_file(&extract_path);
113        return Err(crate::error::GeolithError::Osmium(format!(
114            "osmium extract failed (exit {}) on {}; fix the file or the disk, or remove \
115             osmium from $PATH to read the whole PBF",
116            status
117                .code()
118                .map_or_else(|| "signal".to_owned(), |c| c.to_string()),
119            pbf_path.display(),
120        )));
121    }
122
123    let original_size = std::fs::metadata(pbf_path).map(|m| m.len()).unwrap_or(0);
124    let extract_size = std::fs::metadata(&extract_path)
125        .map(|m| m.len())
126        .unwrap_or(0);
127    let ratio = if original_size > 0 {
128        (extract_size as f64 / original_size as f64) * 100.0
129    } else {
130        0.0
131    };
132
133    tracing::info!(
134        "osmium extract: {} → {} ({:.1}% of original)",
135        humanize_bytes(original_size),
136        humanize_bytes(extract_size),
137        ratio,
138    );
139
140    Ok(ExtractResult {
141        pbf_path: extract_path,
142        is_extracted: true,
143    })
144}
145
146/// Clean up an extracted PBF file.
147///
148/// No-op if `is_extracted` is false or the file doesn't exist.
149pub fn cleanup(result: &ExtractResult) {
150    if result.is_extracted {
151        if let Err(e) = std::fs::remove_file(&result.pbf_path) {
152            tracing::warn!(
153                "Failed to clean up extracted PBF {}: {e}",
154                result.pbf_path.display(),
155            );
156        } else {
157            tracing::info!("Cleaned up extracted PBF: {}", result.pbf_path.display(),);
158        }
159    }
160}
161
162/// Format bytes as a human-readable string.
163#[must_use]
164fn humanize_bytes(bytes: u64) -> String {
165    const KB: u64 = 1024;
166    const MB: u64 = 1024 * KB;
167    const GB: u64 = 1024 * MB;
168
169    if bytes >= GB {
170        format!("{:.1} GiB", bytes as f64 / GB as f64)
171    } else if bytes >= MB {
172        format!("{:.1} MiB", bytes as f64 / MB as f64)
173    } else if bytes >= KB {
174        format!("{:.1} KiB", bytes as f64 / KB as f64)
175    } else {
176        format!("{bytes} B")
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn humanize_bytes_formatting() {
186        assert_eq!(humanize_bytes(0), "0 B");
187        assert_eq!(humanize_bytes(512), "512 B");
188        assert_eq!(humanize_bytes(1024), "1.0 KiB");
189        assert_eq!(humanize_bytes(1536), "1.5 KiB");
190        assert_eq!(humanize_bytes(1_048_576), "1.0 MiB");
191        assert_eq!(humanize_bytes(1_073_741_824), "1.0 GiB");
192    }
193
194    #[test]
195    fn extract_result_not_extracted() {
196        let result = ExtractResult {
197            pbf_path: PathBuf::from("/tmp/planet.osm.pbf"),
198            is_extracted: false,
199        };
200        assert!(!result.is_extracted);
201        // cleanup should be a no-op
202        cleanup(&result);
203    }
204
205    #[test]
206    fn humanize_bytes_partial_units() {
207        assert_eq!(humanize_bytes(2048), "2.0 KiB");
208        assert_eq!(humanize_bytes(2 * 1_048_576), "2.0 MiB");
209        assert_eq!(humanize_bytes(1024 * 1024 * 1024 * 5), "5.0 GiB");
210        assert_eq!(humanize_bytes(1023), "1023 B");
211        assert_eq!(humanize_bytes(1_048_575), "1024.0 KiB");
212    }
213
214    #[test]
215    fn cleanup_removes_extracted_file_when_present() {
216        let dir = tempfile::tempdir().expect("tmp");
217        let path = dir.path().join("geolith-extract.osm.pbf");
218        std::fs::write(&path, b"fake pbf data").expect("write");
219        assert!(path.exists());
220        let result = ExtractResult {
221            pbf_path: path.clone(),
222            is_extracted: true,
223        };
224        cleanup(&result);
225        assert!(!path.exists(), "extracted file should be removed");
226    }
227
228    #[test]
229    fn cleanup_leaves_a_user_supplied_pbf_in_place() {
230        let dir = tempfile::tempdir().expect("tmp");
231        let path = dir.path().join("user-supplied.osm.pbf");
232        std::fs::write(&path, b"fake pbf data").expect("write");
233        let result = ExtractResult {
234            pbf_path: path.clone(),
235            is_extracted: false,
236        };
237
238        cleanup(&result);
239
240        assert!(
241            path.exists(),
242            "cleanup must not delete a PBF the user supplied"
243        );
244    }
245
246    #[test]
247    fn try_extract_falls_back_when_osmium_missing() {
248        if osmium_available("osmium") {
249            return;
250        }
251        let dir = tempfile::tempdir().expect("tmp");
252        let pbf = dir.path().join("planet.osm.pbf");
253        std::fs::write(&pbf, b"fake").expect("write");
254        let bbox = Bbox {
255            min_lon: 0.0,
256            min_lat: 0.0,
257            max_lon: 1.0,
258            max_lat: 1.0,
259        };
260        let result = try_extract(&pbf, &bbox, dir.path()).expect("must not error");
261        assert!(!result.is_extracted);
262        assert_eq!(result.pbf_path, pbf);
263    }
264
265    #[test]
266    fn a_real_osmium_that_rejects_the_file_is_an_error_and_leaves_no_partial_extract() {
267        if !osmium_available("osmium") {
268            return;
269        }
270        let dir = tempfile::tempdir().expect("tmp");
271        let pbf = dir.path().join("garbage.osm.pbf");
272        std::fs::write(&pbf, b"this is not a valid pbf").expect("write");
273        let bbox = Bbox {
274            min_lon: 0.0,
275            min_lat: 0.0,
276            max_lon: 1.0,
277            max_lat: 1.0,
278        };
279        // osmium rejects the garbage file: the build stops, and the partial
280        // extract is removed.
281        let err = try_extract(&pbf, &bbox, dir.path()).expect_err("osmium failed");
282        assert!(
283            crate::error::report(&err).contains("osmium extract failed"),
284            "{}",
285            crate::error::report(&err)
286        );
287        assert!(!dir.path().join("geolith-extract.osm.pbf").exists());
288    }
289
290    /// A stand-in `osmium` that fails: a shell script that exits 1.
291    #[cfg(unix)]
292    fn failing_osmium(dir: &Path) -> PathBuf {
293        use std::os::unix::fs::PermissionsExt as _;
294        let script = dir.join("osmium");
295        std::fs::write(&script, "#!/bin/sh\nexit 1\n").expect("script");
296        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).expect("chmod");
297        script
298    }
299
300    /// A failed `osmium extract` used to log a warning and go on with the
301    /// full PBF: a build meant for a small box ran on the planet for hours.
302    #[cfg(unix)]
303    #[test]
304    fn a_failed_extract_is_an_error() {
305        let dir = tempfile::tempdir().expect("tmp");
306        let bbox = Bbox::parse("7.4,43.7,7.5,43.8").expect("bbox");
307        let program = failing_osmium(dir.path());
308        let err = try_extract_with(
309            program.to_str().expect("utf-8"),
310            Path::new("/data/planet.osm.pbf"),
311            &bbox,
312            dir.path(),
313        )
314        .expect_err("osmium exited 1");
315        let text = crate::error::report(&err);
316        assert!(text.contains("osmium extract failed"), "{text}");
317        assert!(text.contains("exit 1"), "{text}");
318        assert!(text.contains("planet.osm.pbf"), "{text}");
319    }
320
321    /// No `osmium` at all is still not an error: the full PBF is read and
322    /// filtered by box.
323    #[test]
324    fn a_missing_osmium_falls_back_to_the_full_pbf() {
325        let dir = tempfile::tempdir().expect("tmp");
326        let bbox = Bbox::parse("7.4,43.7,7.5,43.8").expect("bbox");
327        let result = try_extract_with(
328            "no-such-program-geolith-test",
329            Path::new("/data/planet.osm.pbf"),
330            &bbox,
331            dir.path(),
332        )
333        .expect("a missing program is a fallback");
334        assert!(!result.is_extracted);
335        assert_eq!(result.pbf_path, Path::new("/data/planet.osm.pbf"));
336    }
337}