Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / scripts / maps / mamaps_build / src / store_part1.rs

store_part1.rs250 lines · 11.0 KiBRaw
1/// A road's extra spill data, grouped for [`Sink::push_road`].
2#[cfg(test)]
3pub struct RoadAttrs<'a> {
4 pub name: Option<&'a str>,
5 pub lane_count: u8,
6 pub turn_fwd: &'a [u16],
7 pub turn_bwd: &'a [u16],
8 pub carriageway: Carriageway,
9}
10
11impl Sink {
12 /// The feature spill stages in anonymous pagefile-backed memory (no `.tmp`
13 /// file, nothing stranded on kill). `path` names nothing — it only rides
14 /// along for error messages.
15 #[cfg(test)]
16 pub fn create(path: impl AsRef<Path>) -> Result<Sink> {
17 Self::create_planned(path, osm_ingest::mem::SpillPlan::Anon)
18 }
19
20 /// Create with an explicit staging plan. See [`osm_ingest::mem::SpillPlan::decide`]: the
21 /// budget gate picks `File` when anon commit does not fit, and `File` stages the same
22 /// records through a `.tmp` beside `path`, removed by `finish`'s caller on success like every
23 /// other scratch file. Same records, same offsets, same bytes -- the backend never changes a
24 /// hash.
25 pub fn create_planned(path: impl AsRef<Path>, plan: osm_ingest::mem::SpillPlan) -> Result<Sink> {
26 let path = path.as_ref();
27 let writer = match plan {
28 osm_ingest::mem::SpillPlan::Anon => {
29 NormalizedWriter::create_anon(std::path::PathBuf::from("anon-spill"))
30 .map_err(|e| osm_ingest::proto::Error(e.to_string()))?
31 }
32 osm_ingest::mem::SpillPlan::File => {
33 eprintln!(" [stage A] feature spill -> {} (file backend: commit budget)", path.display());
34 // Created empty and marked uncompressed first (`create` below truncates the same
35 // inode, keeping the flag): the frames are already DEFLATE, so `compress-force`
36 // spends a zstd attempt per 128 KiB extent at writeback on bytes that will not
37 // shrink -- 289 GB of them on the planet. Best effort; the bytes are the same.
38 if let Ok(file) = std::fs::File::create(path) {
39 osm_ingest::mem::mark_scratch_uncompressed(&file);
40 }
41 NormalizedWriter::create(path)
42 .map_err(|e| osm_ingest::proto::Error(e.to_string()))?
43 }
44 };
45 Ok(Sink {
46 writer,
47 props: vec![(CLASS_KEY.to_string(), Value::Uint(0))],
48 chunk_mins: Vec::new(),
49 filling: u8::MAX,
50 count: 0,
51 bbox: None,
52 })
53 }
54
55 pub fn push(&mut self, class: &Class, geometry: &EncodedGeom) -> Result<()> {
56 self.push_named(class, geometry, None, tilecodec::mamaps::body::ID_NONE)
57 }
58
59 /// TEMP-PROFILE: compressed spill bytes staged so far. Removed with the probes.
60 pub fn staged_bytes(&self) -> u64 {
61 self.writer.staged_bytes()
62 }
63
64 /// Push a transit line: like [`Sink::push`], plus the route colour that becomes the body's
65 /// `transit_color` and the lane inputs that become its `transit_ordinal`, `transit_lanes` and
66 /// `transit_taper`. A zero colour is refused, not written as absent — zero means "no colour"
67 /// on the wire, and a transit line without one is a caller bug, not a pale line.
68 pub fn push_transit(
69 &mut self,
70 class: &Class,
71 geometry: &EncodedGeom,
72 color: u32,
73 ordinal: u8,
74 lanes: u8,
75 taper: u8,
76 ) -> Result<()> {
77 if color == 0 {
78 return err("a transit line with no colour".to_string());
79 }
80 self.props[0].1 = Value::Uint(pack(class)?);
81 self.props.truncate(1);
82 self.props.push((COLOR_KEY.to_string(), Value::Uint(color as u64)));
83 let lane_bits = ((ordinal as u64) << 16) | ((lanes as u64) << 8) | (taper as u64);
84 self.props.push((LANE_KEY.to_string(), Value::Uint(lane_bits)));
85 self.write_record(class, geometry)
86 }
87
88 /// Push a feature with an optional display name (labels: `places` and `poi`) and, for those
89 /// same two layers, the tagged OSM id it came from.
90 ///
91 /// One prop on the wire for the nameless, idless 190 M and up to three for a label: the spill
92 /// encodes a per-record prop count, so variable shapes cost nothing. `feature_of` reads them
93 /// all back.
94 ///
95 /// An id on any layer but `places` or `poi` is refused rather than dropped. Those are the only
96 /// two the archive's id table carries, and a caller passing one elsewhere has misunderstood
97 /// which features have a stable identity — `coalesce` merges lines and areas, so theirs would
98 /// be whichever input happened to survive.
99 pub fn push_named(
100 &mut self,
101 class: &Class,
102 geometry: &EncodedGeom,
103 name: Option<&str>,
104 id: u64,
105 ) -> Result<()> {
106 fill_named(&mut self.props, class, name, id)?;
107 self.write_record(class, geometry)
108 }
109
110 /// Push a road with its carriageway lane count, per-lane turn masks and directional split:
111 /// like [`Sink::push`], plus the optional display name (so a road's label survives even when it
112 /// carries lane data), the lane count (body `lane_count`), the forward/backward `turn:lanes`
113 /// masks (body turn-lane table) and the [`Carriageway`] (body carriageway table). Refused with
114 /// no name and all lane data empty — a plain, nameless road goes through [`Sink::push`] and
115 /// carries no extra property at all, so the spill pays nothing for it.
116 #[cfg(test)]
117 pub fn push_road(
118 &mut self,
119 class: &Class,
120 geometry: &EncodedGeom,
121 road: RoadAttrs<'_>,
122 ) -> Result<()> {
123 fill_road(&mut self.props, class, road.name, road.lane_count, road.turn_fwd, road.turn_bwd, road.carriageway)?;
124 self.write_record(class, geometry)
125 }
126
127 /// Push a building with its S3DB attributes and optional display name. The attributes ride as
128 /// three packed `Uint`s ([`BLD_A_KEY`]/[`BLD_B_KEY`]/[`BLD_C_KEY`]), always written — even for
129 /// an all-default building — so the tiler can build a side table dense-parallel to the
130 /// `buildings` layer. A name is written only when present (a building is rarely named; its
131 /// label is usually a `poi`).
132 #[cfg(test)]
133 pub fn push_building(
134 &mut self,
135 class: &Class,
136 geometry: &EncodedGeom,
137 name: Option<&str>,
138 attrs: BuildingAttrs,
139 ) -> Result<()> {
140 fill_building(&mut self.props, class, name, attrs)?;
141 self.write_record(class, geometry)
142 }
143
144 fn write_record(&mut self, class: &Class, geometry: &EncodedGeom) -> Result<()> {
145 self.writer
146 .push_preencoded(geometry.kind, &geometry.bytes, geometry.bounds, &self.props)
147 .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;
148 self.filling = self.filling.min(class.min_zoom);
149 self.count += 1;
150 // Closed on the same boundary `NormalizedWriter` closes its own chunks on, so entry `i` here
151 // describes chunk `i` there. Off by one and the tiler skips the wrong features.
152 if self.count % NORM_CHUNK_FEATURES == 0 {
153 self.chunk_mins.push(self.filling);
154 self.filling = u8::MAX;
155 }
156 self.grow_bounds(geometry.ebbx);
157 Ok(())
158 }
159
160 /// Extend the bounding box by one geometry's precomputed e7 box.
161 ///
162 /// [`Sink::grow`] walked vertices; the encoder already did on the pool (see
163 /// [`ebbx_of`](crate::store::ebbx_of)). `None` (no vertices at all)
164 /// contributes nothing — identical to the walk visiting nothing.
165 fn grow_bounds(&mut self, ebbx: Option<(i32, i32, i32, i32)>) {
166 let Some((x0, y0, x1, y1)) = ebbx else {
167 return;
168 };
169 match &mut self.bbox {
170 None => self.bbox = Some((x0, y0, x1, y1)),
171 Some(s) => {
172 s.0 = s.0.min(x0);
173 s.1 = s.1.min(y0);
174 s.2 = s.2.max(x1);
175 s.3 = s.3.max(y1);
176 }
177 }
178 }
179
180 pub fn finish(mut self, path: impl Into<PathBuf>) -> Result<Store> {
181 let (count, bbox) = (self.count, self.bbox);
182 // The last chunk is usually partial and still needs an entry.
183 if self.filling != u8::MAX {
184 self.chunk_mins.push(self.filling);
185 }
186 let chunk_mins = std::mem::take(&mut self.chunk_mins);
187 // Anonymous or file-backed depending on the plan `create_planned` took: seal the store and
188 // carry the anon bytes on the `Store`, or `None` when the bytes live in the file at `path`.
189 let (summary, anon) = self
190 .writer
191 .finish_either()
192 .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;
193 let chunks = summary.chunks;
194 // The two indexes must describe the same chunks, or skipping silently drops real features.
195 // Cheap to assert and near-impossible to diagnose from the symptom, which would be missing
196 // geometry in a handful of tiles at one zoom.
197 let expected = chunks.len().saturating_sub(1);
198 if chunk_mins.len() != expected {
199 return err(format!(
200 "the spill has {expected} chunk(s) but {} zoom entr(ies)",
201 chunk_mins.len(),
202 ));
203 }
204 Ok(Store {
205 path: path.into(),
206 anon: anon.map(std::sync::Arc::new),
207 count,
208 bbox: bbox.unwrap_or((0, 0, 0, 0)),
209 chunks,
210 chunk_mins,
211 conventions: crate::schema::boundaries::Conventions::default(),
212 })
213 }
214
215 /// The bounding box of everything pushed so far, in degrees.
216 ///
217 /// `None` until something has been pushed. Used to clip a planet-wide coastline product down to
218 /// the area a build actually covers, which is why it is readable mid-stream.
219 pub fn bbox_degrees(&self) -> Option<(f64, f64, f64, f64)> {
220 let (min_x, min_y, max_x, max_y) = self.bbox?;
221 Some((
222 min_x as f64 * 1e-7,
223 min_y as f64 * 1e-7,
224 max_x as f64 * 1e-7,
225 max_y as f64 * 1e-7,
226 ))
227 }
228}
229
230/// Features staged in anonymous memory or a scratch file, re-readable in order as many times as
231/// the tiler needs. `path` names the file on the `File` plan and nothing on the `Anon` one (it
232/// only rides along for error messages there). `anon` carries the pagefile-backed store when
233/// present; everything else (indexes, counts, conventions) is as before.
234pub struct Store {
235 path: PathBuf,
236 anon: Option<std::sync::Arc<tile_build::anon::AnonStore>>,
237 /// Byte offset of every 64th record, plus a sentinel holding the file length, so chunk `i` spans
238 /// `chunks[i]..chunks[i + 1]` and reads with no knowledge of any other chunk.
239 chunks: Vec<u64>,
240 /// The shallowest `min_zoom` in each chunk.
241 chunk_mins: Vec<u8>,
242 count: u64,
243 bbox: (i32, i32, i32, i32),
244 /// Which marking convention applies where, resolved once from the extract's country relations.
245 ///
246 /// Not a property of the features and so not in the spill: it is one small grid for the whole
247 /// build, read by the tiler once per tile. It rides on the `Store` because that is the one
248 /// thing stage A hands the tiler.
249 conventions: crate::schema::boundaries::Conventions,
250}