Skip to main content

geocoder_core/index/
import.rs

1//! Build an index file from a data source, atomically.
2
3use std::io::{BufRead, BufReader, Read};
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8use super::IndexBuilder;
9use crate::doc::Document;
10use crate::error::GeocoderError;
11use crate::profile::Profile;
12use crate::readers::{Source, be, for_each_input, grouped::Grouper, lu};
13
14/// Progress, reported every `PROGRESS_EVERY` lines.
15#[derive(Debug, Clone, Copy)]
16pub struct ImportProgress {
17    pub lines: usize,
18    pub documents: usize,
19    pub elapsed: Duration,
20}
21
22#[derive(Debug, Clone, Copy)]
23pub struct ImportStats {
24    pub documents: usize,
25    /// Rejected documents (missing required field or coordinates).
26    pub skipped: usize,
27    /// Lines that could not be parsed.
28    pub invalid: usize,
29    pub elapsed: Duration,
30}
31
32pub const PROGRESS_EVERY: usize = 200_000;
33
34/// Index every document of `reader` and write the index to `output`.
35///
36/// The index is written to a temporary file next to `output`, then renamed:
37/// a process opening `output` meanwhile sees the previous index, never a
38/// partial one. Invalid lines are counted and skipped.
39pub fn import(
40    reader: impl BufRead,
41    source: Source,
42    profile: Arc<dyn Profile>,
43    output: &Path,
44    progress: impl FnMut(ImportProgress),
45) -> Result<ImportStats, GeocoderError> {
46    let mut importer = Importer::new(profile, progress);
47    let mut reader = reader;
48    importer.read(&mut reader, source)?;
49    importer.finish(output)
50}
51
52/// [`import`] over several files (e.g. the three regions of Belgium), each
53/// a plain, `.gz` or `.zip` file.
54pub fn import_files(
55    inputs: &[PathBuf],
56    source: Source,
57    profile: Arc<dyn Profile>,
58    output: &Path,
59    progress: impl FnMut(ImportProgress),
60) -> Result<ImportStats, GeocoderError> {
61    let mut importer = Importer::new(profile, progress);
62    for input in inputs {
63        for_each_input(input, |reader| importer.read(reader, source))?;
64    }
65    importer.finish(output)
66}
67
68struct Importer<P> {
69    builder: IndexBuilder,
70    progress: P,
71    started: Instant,
72    lines: usize,
73    invalid: usize,
74    /// A register's streets, turned into documents once every input is
75    /// read (Belgium comes in one file per region).
76    grouper: Option<Grouper>,
77}
78
79impl<P: FnMut(ImportProgress)> Importer<P> {
80    fn new(profile: Arc<dyn Profile>, progress: P) -> Self {
81        Self {
82            builder: IndexBuilder::new(profile),
83            progress,
84            started: Instant::now(),
85            lines: 0,
86            invalid: 0,
87            grouper: None,
88        }
89    }
90
91    fn read(&mut self, reader: &mut dyn Read, source: Source) -> Result<(), GeocoderError> {
92        match source {
93            Source::Addok | Source::Bano => {
94                for line in BufReader::new(reader).lines() {
95                    let line = line?;
96                    match source.parse(&line) {
97                        Ok(Some(doc)) => {
98                            self.builder.add_document(doc)?;
99                        }
100                        Ok(None) => {}
101                        Err(_) => self.invalid += 1,
102                    }
103                    self.tick();
104                }
105            }
106            Source::Lu | Source::Be => {
107                let grouper = self
108                    .grouper
109                    .get_or_insert_with(|| Grouper::new(source.name()));
110                let mut lines = 0usize;
111                let invalid = if source == Source::Lu {
112                    lu::for_each_row(reader, |row| {
113                        grouper.add(row);
114                        lines += 1;
115                    })?
116                } else {
117                    be::for_each_row(reader, |row| {
118                        grouper.add(row);
119                        lines += 1;
120                    })?
121                };
122                self.invalid += invalid;
123                self.lines += lines;
124            }
125        }
126        Ok(())
127    }
128
129    fn add_all(&mut self, docs: Vec<Document>) -> Result<(), GeocoderError> {
130        for doc in docs {
131            self.builder.add_document(doc)?;
132            self.tick();
133        }
134        Ok(())
135    }
136
137    fn tick(&mut self) {
138        self.lines += 1;
139        if self.lines.is_multiple_of(PROGRESS_EVERY) {
140            (self.progress)(ImportProgress {
141                lines: self.lines,
142                documents: self.builder.documents(),
143                elapsed: self.started.elapsed(),
144            });
145        }
146    }
147
148    fn finish(mut self, output: &Path) -> Result<ImportStats, GeocoderError> {
149        if let Some(grouper) = self.grouper.take() {
150            self.add_all(grouper.finish())?;
151        }
152        let (documents, skipped) = (self.builder.documents(), self.builder.skipped());
153        if documents == 0 {
154            return Err(GeocoderError::InvalidIndex("no document to index"));
155        }
156
157        let tmp = temporary_path(output);
158        if let Err(e) = self.builder.build(&tmp) {
159            let _ = std::fs::remove_file(&tmp);
160            return Err(e);
161        }
162        std::fs::rename(&tmp, output)?;
163        Ok(ImportStats {
164            documents,
165            skipped,
166            invalid: self.invalid,
167            elapsed: self.started.elapsed(),
168        })
169    }
170}
171
172fn temporary_path(output: &Path) -> PathBuf {
173    let mut name = output
174        .file_name()
175        .map(|n| n.to_os_string())
176        .unwrap_or_default();
177    name.push(".tmp");
178    output.with_file_name(name)
179}