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

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

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