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

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

store_part2.rs357 lines · 14.1 KiBRaw
1impl Store {
2 /// How many features are in the file.
3 #[cfg_attr(not(test), allow(dead_code))]
4 pub fn len(&self) -> u64 {
5 self.count
6 }
7
8 /// The bounding box of every feature, in degrees times 1e7, for the archive header.
9 pub fn bbox(&self) -> (i32, i32, i32, i32) {
10 self.bbox
11 }
12
13 /// Read every feature a zoom could want, in the order they were written.
14 ///
15 /// A chunk whose shallowest `min_zoom` is deeper than `z` holds nothing this zoom draws, so it is
16 /// skipped outright — not read, not parsed. Order is unchanged, because the chunks that survive
17 /// are still visited in file order, and that is what keeps the archive byte-identical.
18 pub fn reader_for_zoom(&self, z: u8) -> Result<ZoomReader> {
19 let wanted: Vec<usize> = self
20 .chunk_mins
21 .iter()
22 .enumerate()
23 .filter(|(_, min)| **min <= z)
24 .map(|(i, _)| i)
25 .collect();
26 self.reader_for_wanted(wanted, z)
27 }
28
29 pub fn wanted_chunks_for_zoom(&self, z: u8) -> Vec<usize> {
30 self.chunk_mins
31 .iter()
32 .enumerate()
33 .filter(|(_, min)| **min <= z)
34 .map(|(i, _)| i)
35 .collect()
36 }
37
38 pub fn wanted_len_for_zoom(&self, z: u8) -> usize {
39 self.chunk_mins.iter().filter(|min| **min <= z).count()
40 }
41
42 pub fn path(&self) -> &PathBuf {
43 &self.path
44 }
45
46 /// The shared anonymous spill store. Cloned (refcount bump, never bytes)
47 /// into per-lane store views so decode threads read the same memory.
48 /// `None` on the file plan, where lanes open the file at `path` instead.
49 pub fn anon_store(&self) -> Option<std::sync::Arc<tile_build::anon::AnonStore>> {
50 self.anon.clone()
51 }
52
53 pub fn raw_chunks(&self) -> &[u64] {
54 &self.chunks
55 }
56
57 pub fn chunk_mins_cloned(&self) -> Vec<u8> {
58 self.chunk_mins.clone()
59 }
60
61 pub fn from_parts(path: PathBuf, chunks: Vec<u64>, chunk_mins: Vec<u8>) -> Self {
62 Self {
63 path,
64 anon: None,
65 chunks,
66 chunk_mins,
67 count: 0,
68 bbox: (0, 0, 0, 0),
69 conventions: crate::schema::boundaries::Conventions::default(),
70 }
71 }
72
73 /// A view over the same staged bytes: `store` is the shared anonymous
74 /// spill (cloned Arc, never bytes) or `None` on the file plan, where the view reads the file
75 /// at `path`. `chunks`/`chunk_mins` the same index either way.
76 /// Used by per-lane decode threads, which need a `Store` to open readers
77 /// from but must not copy the spill.
78 pub fn view_over(
79 path: PathBuf,
80 chunks: Vec<u64>,
81 chunk_mins: Vec<u8>,
82 store: Option<std::sync::Arc<tile_build::anon::AnonStore>>,
83 ) -> Self {
84 Self {
85 path,
86 anon: store,
87 chunks,
88 chunk_mins,
89 count: 0,
90 bbox: (0, 0, 0, 0),
91 conventions: crate::schema::boundaries::Conventions::default(),
92 }
93 }
94
95 /// Open the staged bytes for chunked reading, anonymous or file according to the plan the
96 /// sink was created with. One helper so the three reader constructors agree.
97 fn open_chunks(&self) -> Result<NormalizedChunks> {
98 match &self.anon {
99 Some(store) => NormalizedChunks::open_anon(
100 self.path.clone(),
101 self.chunks.clone(),
102 std::sync::Arc::clone(store),
103 )
104 .map_err(|e| osm_ingest::proto::Error(e.to_string())),
105 None => NormalizedChunks::open(self.path.clone(), self.chunks.clone())
106 .map_err(|e| osm_ingest::proto::Error(e.to_string())),
107 }
108 }
109
110 /// Open the staged bytes for sequential reading. See [`open_chunks`](Self::open_chunks).
111 fn open_sequential(&self) -> Result<NormalizedReader> {
112 match &self.anon {
113 Some(store) => NormalizedReader::open_anon(
114 self.path.clone(),
115 std::sync::Arc::clone(store),
116 )
117 .map_err(|e| osm_ingest::proto::Error(e.to_string())),
118 None => NormalizedReader::open(self.path.clone())
119 .map_err(|e| osm_ingest::proto::Error(e.to_string())),
120 }
121 }
122
123 /// Attach the anonymous store after construction. Used by tests that build
124 /// a `Store` from parts and then read it back without a file.
125 #[cfg(test)]
126 pub fn with_anon(
127 mut self,
128 store: std::sync::Arc<tile_build::anon::AnonStore>,
129 ) -> Self {
130 self.anon = Some(store);
131 self
132 }
133
134 /// Take the marking-convention grid stage A resolved from the country relations.
135 pub fn with_conventions(
136 mut self,
137 conventions: crate::schema::boundaries::Conventions,
138 ) -> Self {
139 self.conventions = conventions;
140 self
141 }
142
143 /// Which marking convention applies where, for the tiler to stamp onto each tile.
144 pub fn conventions(&self) -> &crate::schema::boundaries::Conventions {
145 &self.conventions
146 }
147
148 pub fn reader_for_wanted(&self, wanted: Vec<usize>, z: u8) -> Result<ZoomReader> {
149 let chunks = self.open_chunks()?;
150 ZoomReader::spawn(chunks, wanted, z)
151 }
152
153 /// Read every feature, in the order they were written.
154 ///
155 /// Kept as the reference [`Self::reader_for_zoom`] is checked against: a test that reads a store
156 /// both ways and compares is the cheapest possible guard on the chunk index being right.
157 #[cfg_attr(not(test), allow(dead_code))]
158 pub fn reader(&self) -> Result<Reader> {
159 Ok(Reader { inner: self.open_sequential()? })
160 }
161}
162
163impl Store {
164 /// Spill features from memory into a temporary store.
165 ///
166 /// For tests only. The generator never has a `Vec<Feature>` to hand -- that is the entire point
167 /// of this module -- but a test that had to write a file to state its case would be a worse test.
168 #[cfg(test)]
169 pub fn of(features: &[Feature]) -> Result<Store> {
170 use std::sync::atomic::{AtomicU64, Ordering};
171 static NEXT: AtomicU64 = AtomicU64::new(0);
172 let path = std::env::temp_dir().join(format!(
173 "mamaps_test_{}_{}.features",
174 std::process::id(),
175 NEXT.fetch_add(1, Ordering::Relaxed),
176 ));
177 let mut sink = Sink::create(&path)?;
178 for feature in features {
179 // Test-only path: encode inline (the pool-built path is exercised
180 // by the materialise drains, not here).
181 let encoded = EncodedGeom::live(&feature.geometry)?;
182 if feature.transit_color != 0 {
183 sink.push_transit(
184 &feature.class,
185 &encoded,
186 feature.transit_color,
187 feature.transit_ordinal,
188 feature.transit_lanes,
189 feature.transit_taper,
190 )?;
191 } else if let Some(attrs) = feature.building {
192 sink.push_building(
193 &feature.class,
194 &encoded,
195 feature.name.as_deref(),
196 attrs,
197 )?;
198 } else if feature.lane_count != 0
199 || !feature.turn_fwd.is_empty()
200 || !feature.turn_bwd.is_empty()
201 || !feature.carriageway.is_empty()
202 {
203 sink.push_road(
204 &feature.class,
205 &encoded,
206 feature.name.as_deref(),
207 feature.lane_count,
208 &feature.turn_fwd,
209 &feature.turn_bwd,
210 feature.carriageway,
211 )?;
212 } else {
213 sink.push_named(&feature.class, &encoded, feature.name.as_deref(), feature.id)?;
214 }
215 }
216 sink.finish(&path)
217 }
218}
219
220/// A spilled record as a [`Feature`].
221///
222/// A record whose class property is missing or is not an integer is a corrupt file rather than a
223/// feature to skip: everything in here was written by [`Sink::push`] one run ago, so anything else
224/// means the file is not the one we wrote. A `n` string property rides along as the display
225/// name, a `t` integer as the transit colour, an `s` integer as its packed lane inputs and an `i`
226/// integer as the tagged OSM id; anything else in there is corruption for the same reason.
227fn feature_of(record: tile_build::spill::NormalizedFeature) -> Result<Feature> {
228 let bits = match record.props.iter().find(|(key, _)| key == CLASS_KEY) {
229 Some((_, Value::Uint(bits))) => *bits,
230 _ => return err("a spilled feature carries no packed class".to_string()),
231 };
232 let mut name: Option<String> = None;
233 let mut id: u64 = tilecodec::mamaps::body::ID_NONE;
234 let mut transit_color: u32 = 0;
235 let mut transit_ordinal: u8 = 0;
236 let mut transit_lanes: u8 = 0;
237 let mut transit_taper: u8 = 0;
238 let mut lane_count: u8 = 0;
239 let mut turn_fwd: Vec<u16> = Vec::new();
240 let mut turn_bwd: Vec<u16> = Vec::new();
241 let mut carriageway = Carriageway::default();
242 let mut bld_a: Option<u64> = None;
243 let mut bld_b: Option<u64> = None;
244 let mut bld_c: Option<u64> = None;
245 for (key, value) in &record.props {
246 if key == CLASS_KEY {
247 continue;
248 }
249 match (key.as_str(), value) {
250 (NAME_KEY, Value::String(text)) if !text.is_empty() => {
251 if name.replace(text.clone()).is_some() {
252 return err("a spilled feature carries two names".to_string());
253 }
254 }
255 (COLOR_KEY, Value::Uint(color)) => {
256 transit_color = u32::try_from(*color)
257 .map_err(|_| Error("a spilled transit colour does not fit u32".to_string()))?;
258 }
259 (LANE_KEY, Value::Uint(lane_bits)) => {
260 if *lane_bits > 0xff_ff_ff {
261 return err("a spilled transit lane triple does not fit three bytes".to_string());
262 }
263 transit_ordinal = (lane_bits >> 16) as u8;
264 transit_lanes = (lane_bits >> 8) as u8;
265 transit_taper = *lane_bits as u8;
266 }
267 (LANE_COUNT_KEY, Value::Uint(count)) => {
268 lane_count = u8::try_from(*count)
269 .map_err(|_| Error("a spilled road lane count does not fit a byte".to_string()))?;
270 }
271 (TURN_FWD_KEY, Value::String(packed)) => {
272 turn_fwd = unpack_lanes(packed)?;
273 }
274 (TURN_BWD_KEY, Value::String(packed)) => {
275 turn_bwd = unpack_lanes(packed)?;
276 }
277 (CARRIAGEWAY_KEY, Value::Uint(bits)) => {
278 carriageway = unpack_carriageway(*bits);
279 }
280 (BLD_A_KEY, Value::Uint(v)) => bld_a = Some(*v),
281 (BLD_B_KEY, Value::Uint(v)) => bld_b = Some(*v),
282 (BLD_C_KEY, Value::Uint(v)) => bld_c = Some(*v),
283 (ID_KEY, Value::Uint(tagged)) => {
284 if id != tilecodec::mamaps::body::ID_NONE {
285 return err("a spilled feature carries two ids".to_string());
286 }
287 id = *tagged;
288 }
289 _ => {
290 return err(format!("a spilled feature carries an unknown property `{key}`"));
291 }
292 }
293 }
294 Ok(Feature {
295 class: unpack(bits),
296 geometry: record.geometry,
297 name,
298 id,
299 transit_color,
300 transit_ordinal,
301 transit_lanes,
302 transit_taper,
303 lane_count,
304 turn_fwd,
305 turn_bwd,
306 carriageway,
307 building: match (bld_a, bld_b, bld_c) {
308 (Some(a), Some(b), Some(c)) => Some(unpack_building(a, b, c)),
309 (None, None, None) => None,
310 _ => return err("a spilled building is missing part of its attributes".to_string()),
311 },
312 })
313}
314
315/// Chunks of features as the lanes hand them over, or the error that stopped one.
316///
317/// [`Feature`] rather than the decoder's own record, because turning one into the other is where
318/// the reader thread's remaining time went. It looks like a field lookup and a move, and the field
319/// lookup and the move are free; what is not is dropping the `props` the decoder built — a `Vec` and
320/// an owned key `String` per feature, freed one at a time on the one thread the whole map phase
321/// waits on. Converting in the lane puts that on the lane.
322type Decoded = Result<Vec<Feature>>;
323
324/// Threads decoding spill chunks ahead of the tiler.
325///
326/// Not the pool: see [`ZoomReader::spawn`]. **Four is the safe default, not the right answer**, and
327/// there is no right answer available as a constant. The two extracts want opposite things:
328///
329/// | lanes / tiling workers | us-west | north-america |
330/// |---|---|---|
331/// | 4 / 64 | **91.9 s** | 945.7 s |
332/// | 16 / 64 | 151.9 s | **766.9 s** |
333/// | 16 / 48 | 94.4 s | 900.4 s |
334///
335/// Sixteen lanes is a 65% regression on us-west and a 19% improvement on north-america, and the
336/// mechanism is the same in both: a lane competes for a CPU only when it is running. On
337/// north-america the reader cannot fill the channel fast enough, so the clipping workers are blocked
338/// and the lanes are free; on us-west the workers saturate the machine and the lanes take CPU from
339/// the single reader thread they exist to feed. Which regime a build lands in depends on the spill
340/// against the page cache, not on anything this constant can see — the middle row of that table is
341/// the attempt to correct for it by taking the lanes out of the worker budget, and it makes each
342/// case worse than that case's own best.
343///
344/// So it is a knob, defaulting to the value that cannot hurt. `MAPS_PREFETCH_LANES=16` is what a
345/// continent wants. Removing the need for the knob means removing the re-decode it is compensating
346/// for: the spill is read once per zoom, which is ~1.06 billion feature decodes to deliver
347/// 199.7 M distinct features on north-america, and no lane count makes redundant work cheap.
348pub fn prefetch_lanes() -> usize {
349 static LANES: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
350 *LANES.get_or_init(|| {
351 std::env::var("MAPS_PREFETCH_LANES")
352 .ok()
353 .and_then(|raw| raw.trim().parse::<usize>().ok())
354 .filter(|n| *n > 0)
355 .unwrap_or(4)
356 })
357}