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 span = import_span(source, output);
47    let _entered = span.enter();
48    let mut importer = Importer::new(profile, progress);
49    let mut reader = reader;
50    importer.read(&mut reader, source)?;
51    record(&span, importer.finish(output))
52}
53
54/// [`import`] over several files (e.g. the three regions of Belgium), each
55/// a plain, `.gz` or `.zip` file.
56pub fn import_files(
57    inputs: &[PathBuf],
58    source: Source,
59    profile: Arc<dyn Profile>,
60    output: &Path,
61    progress: impl FnMut(ImportProgress),
62) -> Result<ImportStats, GeocoderError> {
63    let span = import_span(source, output);
64    let _entered = span.enter();
65    let mut importer = Importer::new(profile, progress);
66    for input in inputs {
67        for_each_input(input, |reader| importer.read(reader, source))?;
68    }
69    record(&span, importer.finish(output))
70}
71
72/// `geocoder.import` (INFO), around reading the sources and writing the
73/// index (`geocoder.write`).
74fn import_span(source: Source, output: &Path) -> tracing::Span {
75    tracing::info_span!(
76        "geocoder.import",
77        sentry.op = "geocoder.import",
78        source = source.name(),
79        output = %output.display(),
80        documents = tracing::field::Empty,
81        skipped = tracing::field::Empty,
82        invalid = tracing::field::Empty,
83    )
84}
85
86fn record(
87    span: &tracing::Span,
88    stats: Result<ImportStats, GeocoderError>,
89) -> Result<ImportStats, GeocoderError> {
90    if let Ok(stats) = &stats {
91        span.record("documents", stats.documents);
92        span.record("skipped", stats.skipped);
93        span.record("invalid", stats.invalid);
94    }
95    stats
96}
97
98struct Importer<P> {
99    builder: IndexBuilder,
100    progress: P,
101    started: Instant,
102    lines: usize,
103    invalid: usize,
104    /// A register's streets, turned into documents once every input is
105    /// read (Belgium comes in one file per region).
106    grouper: Option<Grouper>,
107}
108
109impl<P: FnMut(ImportProgress)> Importer<P> {
110    fn new(profile: Arc<dyn Profile>, progress: P) -> Self {
111        Self {
112            builder: IndexBuilder::new(profile),
113            progress,
114            started: Instant::now(),
115            lines: 0,
116            invalid: 0,
117            grouper: None,
118        }
119    }
120
121    fn read(&mut self, reader: &mut dyn Read, source: Source) -> Result<(), GeocoderError> {
122        match source {
123            Source::Addok | Source::Bano => {
124                for line in BufReader::new(reader).lines() {
125                    let line = line?;
126                    match source.parse(&line) {
127                        Ok(Some(doc)) => {
128                            self.builder.add_document(doc)?;
129                        }
130                        Ok(None) => {}
131                        Err(_) => self.invalid += 1,
132                    }
133                    self.tick();
134                }
135            }
136            Source::Lu | Source::Be => {
137                let grouper = self
138                    .grouper
139                    .get_or_insert_with(|| Grouper::new(source.name()));
140                let mut lines = 0usize;
141                let invalid = if source == Source::Lu {
142                    lu::for_each_row(reader, |row| {
143                        grouper.add(row);
144                        lines += 1;
145                    })?
146                } else {
147                    be::for_each_row(reader, |row| {
148                        grouper.add(row);
149                        lines += 1;
150                    })?
151                };
152                self.invalid += invalid;
153                self.lines += lines;
154            }
155        }
156        Ok(())
157    }
158
159    fn add_all(&mut self, docs: Vec<Document>) -> Result<(), GeocoderError> {
160        for doc in docs {
161            self.builder.add_document(doc)?;
162            self.tick();
163        }
164        Ok(())
165    }
166
167    fn tick(&mut self) {
168        self.lines += 1;
169        if self.lines.is_multiple_of(PROGRESS_EVERY) {
170            (self.progress)(ImportProgress {
171                lines: self.lines,
172                documents: self.builder.documents(),
173                elapsed: self.started.elapsed(),
174            });
175        }
176    }
177
178    fn finish(mut self, output: &Path) -> Result<ImportStats, GeocoderError> {
179        if let Some(grouper) = self.grouper.take() {
180            self.add_all(grouper.finish())?;
181        }
182        let (documents, skipped) = (self.builder.documents(), self.builder.skipped());
183        if documents == 0 {
184            return Err(GeocoderError::InvalidIndex("no document to index"));
185        }
186
187        let tmp = temporary_path(output);
188        let built = tracing::info_span!("geocoder.write", sentry.op = "geocoder.write", documents)
189            .in_scope(|| self.builder.build(&tmp));
190        if let Err(e) = built {
191            let _ = std::fs::remove_file(&tmp);
192            return Err(e);
193        }
194        std::fs::rename(&tmp, output)?;
195        Ok(ImportStats {
196            documents,
197            skipped,
198            invalid: self.invalid,
199            elapsed: self.started.elapsed(),
200        })
201    }
202}
203
204fn temporary_path(output: &Path) -> PathBuf {
205    let mut name = output
206        .file_name()
207        .map(|n| n.to_os_string())
208        .unwrap_or_default();
209    name.push(".tmp");
210    output.with_file_name(name)
211}