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