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

Modern-Apps.git / scripts / maps / tile_build / src / spill_part1.rs

spill_part1.rs430 lines · 15.1 KiBRaw
1fn decode_props(b: &[u8]) -> Result<Vec<(String, Value)>> {
2 let mut c = Cur::new(b);
3 let n = c.u32()? as usize;
4 let mut out = Vec::with_capacity(n.min(1 << 12));
5 for _ in 0..n {
6 let key_len = c.u32()? as usize;
7 let key = std::str::from_utf8(c.take(key_len)?)
8 .map_err(|e| Error(format!("spill property key is not UTF-8: {e}")))?
9 .to_string();
10 let tag = c.u8()?;
11 let value = match tag {
12 0 => {
13 let len = c.u32()? as usize;
14 Value::String(
15 std::str::from_utf8(c.take(len)?)
16 .map_err(|e| Error(format!("spill property value is not UTF-8: {e}")))?
17 .to_string(),
18 )
19 }
20 1 => Value::Float(f32::from_bits(c.u32()?)),
21 2 => Value::Double(f64::from_bits(c.u64()?)),
22 3 => Value::Int(c.i64()?),
23 4 => Value::Uint(c.u64()?),
24 5 => Value::SInt(c.i64()?),
25 6 => Value::Bool(c.u8()? != 0),
26 other => return err(format!("spill property has value type {other}")),
27 };
28 out.push((key, value));
29 }
30 if !c.at_end() {
31 return err(format!(
32 "spill properties decoded {} of {} byte(s)",
33 c.consumed(),
34 b.len()
35 ));
36 }
37 Ok(out)
38}
39
40// --- the spill record --------------------------------------------------------
41
42/// One feature's contribution to one tile, as a bucket stores it.
43///
44/// Already clipped, moved into the tile and simplified: the bucket pass does that work
45/// once and the encode pass does none of it. `extent` is the importance proxy, computed
46/// there too, so the encode pass's sort is a comparison of two integers.
47#[derive(Debug, Clone, PartialEq)]
48pub struct SpillRecord {
49 pub tile_id: u64,
50 /// The feature's position in the input. What makes the drop policy's order total,
51 /// and the key the props-normalizing variant of this format would use.
52 pub seq: u64,
53 pub extent: i64,
54 pub geom: IntGeometry,
55 pub props: Vec<(String, Value)>,
56}
57
58impl SpillRecord {
59 /// Append the wire form of this record to `out`.
60 pub fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
61 encode_record(
62 self.tile_id,
63 self.seq,
64 self.extent,
65 &self.geom,
66 &self.props,
67 out,
68 )
69 }
70
71 /// The whole record, ready to hand to [`BucketSet::push`].
72 pub fn to_bytes(&self) -> Result<Vec<u8>> {
73 let mut out = Vec::new();
74 self.encode(&mut out)?;
75 Ok(out)
76 }
77}
78
79/// Append one record's wire form to `out`, without owning it first.
80///
81/// The bucket pass has a borrowed geometry and a borrowed property list and writes the
82/// same feature's properties once per touched tile; building a [`SpillRecord`] to encode
83/// it would clone them forty times over for nothing.
84///
85/// ```text
86/// 0..4 u32 rec_len whole record, this field included
87/// 4..12 u64 tile_id
88/// 12..20 u64 seq
89/// 20..28 i64 extent
90/// 28..32 u32 geom_len
91/// 32..36 u32 props_len
92/// 36..37 u8 geom_kind
93/// 37..48 reserved, zero
94/// 48.. geometry, then properties
95/// ```
96pub fn encode_record(
97 tile_id: u64,
98 seq: u64,
99 extent: i64,
100 geom: &IntGeometry,
101 props: &[(String, Value)],
102 out: &mut Vec<u8>,
103) -> Result<()> {
104 let start = out.len();
105 out.resize(start + REC_HEADER_BYTES, 0);
106 encode_int_geometry(geom, out)?;
107 let geom_len = count(out.len() - start - REC_HEADER_BYTES)?;
108 encode_props(props, out)?;
109 let props_len = count(out.len() - start - REC_HEADER_BYTES - geom_len as usize)?;
110 let rec_len = count(out.len() - start)?;
111
112 let h = &mut out[start..start + REC_HEADER_BYTES];
113 h[0..4].copy_from_slice(&rec_len.to_le_bytes());
114 h[4..12].copy_from_slice(&tile_id.to_le_bytes());
115 h[12..20].copy_from_slice(&seq.to_le_bytes());
116 h[20..28].copy_from_slice(&extent.to_le_bytes());
117 h[28..32].copy_from_slice(&geom_len.to_le_bytes());
118 h[32..36].copy_from_slice(&props_len.to_le_bytes());
119 h[36] = GeomKind::of_int(geom).tag();
120 Ok(())
121}
122
123/// A record header, as read off disk.
124struct RecHeader {
125 rec_len: u32,
126 tile_id: u64,
127 seq: u64,
128 extent: i64,
129 geom_len: u32,
130 props_len: u32,
131 kind: GeomKind,
132}
133
134impl RecHeader {
135 fn parse(b: &[u8; REC_HEADER_BYTES]) -> Result<RecHeader> {
136 let u32_at = |o: usize| u32::from_le_bytes(b[o..o + 4].try_into().expect("4 bytes"));
137 let u64_at = |o: usize| u64::from_le_bytes(b[o..o + 8].try_into().expect("8 bytes"));
138 // A newer writer would use these, so a nonzero tail means the reader is the
139 // wrong version for the file. Guessing would decode a field that has moved.
140 if b[37..REC_HEADER_BYTES].iter().any(|v| *v != 0) {
141 return err("spill record has a nonzero reserved tail");
142 }
143 let rec_len = u32_at(0);
144 let geom_len = u32_at(28);
145 let props_len = u32_at(32);
146 let want = REC_HEADER_BYTES as u64 + geom_len as u64 + props_len as u64;
147 if rec_len as u64 != want {
148 return err(format!(
149 "spill record claims {rec_len} byte(s) but its header adds up to {want}"
150 ));
151 }
152 if want > MAX_RECORD_BYTES {
153 return err(format!("spill record is {want} byte(s), which is corruption"));
154 }
155 Ok(RecHeader {
156 rec_len,
157 tile_id: u64_at(4),
158 seq: u64_at(12),
159 extent: i64::from_le_bytes(b[20..28].try_into().expect("8 bytes")),
160 geom_len,
161 props_len,
162 kind: GeomKind::from_tag(b[36])?,
163 })
164 }
165}
166
167// --- buckets -----------------------------------------------------------------
168
169/// `tile_id`-range buckets for one zoom, or for one over-budget bucket's sub-range.
170///
171/// Bucket `i` holds every `tile_id` in `[lo + i*span, lo + (i+1)*span)`, so the index is
172/// monotonic in `tile_id`: draining buckets in ascending index, each sorted, gives
173/// globally ascending `tile_id`.
174///
175/// The bucket count is a power of four and the range is a power of four, so `span` is
176/// too and a bucket is exactly one quadtree cell's descendants. That keeps a bucket
177/// spatially coherent, which is what makes a re-partition of a dense metro bucket
178/// productive rather than splitting the same crowd four ways.
179///
180/// **The count must stay under the process's file-descriptor limit.** Files are opened
181/// lazily, so a shallow zoom with a handful of occupied ranges only creates a handful —
182/// but a dense zoom will hold every one of them open at once. 256 is the default and
183/// safe everywhere; a few thousand is not, and this deliberately does not paper over it
184/// with a handle cache.
185pub struct BucketSet {
186 dir: PathBuf,
187 /// First `tile_id` this set covers.
188 lo: u64,
189 /// One past the last `tile_id` this set covers.
190 hi: u64,
191 span: u64,
192 paths: Vec<PathBuf>,
193 files: Vec<Option<BufWriter<File>>>,
194 /// Tallied at push time from each record's own `tile_id`. The reader re-derives both
195 /// from the bytes on disk, and [`BucketSet::seal`] asserts they agree with each
196 /// other and with the file length.
197 records: Vec<u64>,
198 bytes: Vec<u64>,
199 pushed: u64,
200 pushed_bytes: u64,
201 sealed: bool,
202}
203
204impl BucketSet {
205 /// `name` distinguishes one set's files from another's in the same directory, so a
206 /// zoom and its re-partitions do not collide.
207 ///
208 /// `hi - lo` must be positive; it is a power of four in every use here.
209 pub fn new(
210 dir: impl Into<PathBuf>,
211 name: &str,
212 lo: u64,
213 hi: u64,
214 want_buckets: usize,
215 ) -> Result<BucketSet> {
216 if hi <= lo {
217 return err(format!("bucket set range {lo}..{hi} is empty"));
218 }
219 if want_buckets == 0 {
220 return err("bucket set needs at least one bucket");
221 }
222 if !want_buckets.is_power_of_two() || want_buckets.trailing_zeros() % 2 != 0 {
223 return err(format!(
224 "bucket count must be a power of four so a bucket is one quadtree cell, got \
225 {want_buckets}"
226 ));
227 }
228 let range = hi - lo;
229 // A shallow zoom has fewer tiles than the requested bucket count. Dividing by
230 // four keeps the quadtree property that clamping to `range` would break.
231 let mut n = want_buckets as u64;
232 while n > 1 && n > range {
233 n /= 4;
234 }
235 let span = range.div_ceil(n);
236 let n = range.div_ceil(span) as usize;
237
238 let dir = dir.into();
239 std::fs::create_dir_all(&dir)
240 .map_err(|e| Error(format!("cannot create {}: {e}", dir.display())))?;
241 let paths: Vec<PathBuf> = (0..n)
242 .map(|i| dir.join(format!("{name}.{i:05}.bucket")))
243 .collect();
244 // A bucket that receives no records is never opened, so `File::create`'s truncate
245 // would not clear a file a SIGKILLed run left at the same path -- and `seal`
246 // would then report bytes on disk that nobody pushed. With an operator-supplied
247 // --spill-dir that turns a crash into a baffling failure on the next attempt.
248 for p in &paths {
249 let _ = std::fs::remove_file(p);
250 }
251 Ok(BucketSet {
252 dir,
253 lo,
254 hi,
255 span,
256 paths,
257 files: (0..n).map(|_| None).collect(),
258 records: vec![0; n],
259 bytes: vec![0; n],
260 pushed: 0,
261 pushed_bytes: 0,
262 sealed: false,
263 })
264 }
265
266 pub fn len(&self) -> usize {
267 self.paths.len()
268 }
269
270 pub fn is_empty(&self) -> bool {
271 self.paths.is_empty()
272 }
273
274 pub fn span(&self) -> u64 {
275 self.span
276 }
277
278 /// `[lo, hi)` of bucket `i`, clamped to the set's own range.
279 pub fn range_of(&self, i: usize) -> (u64, u64) {
280 let lo = self.lo + i as u64 * self.span;
281 (lo, (lo + self.span).min(self.hi))
282 }
283
284 pub fn records_in(&self, i: usize) -> u64 {
285 self.records[i]
286 }
287
288 pub fn bytes_in(&self, i: usize) -> u64 {
289 self.bytes[i]
290 }
291
292 pub fn total_records(&self) -> u64 {
293 self.pushed
294 }
295
296 fn index_of(&self, tile_id: u64) -> Result<usize> {
297 if tile_id < self.lo || tile_id >= self.hi {
298 return err(format!(
299 "tile id {tile_id} is outside the bucket set's range {}..{}",
300 self.lo, self.hi
301 ));
302 }
303 Ok(((tile_id - self.lo) / self.span) as usize)
304 }
305
306 /// Append one already-encoded record to whichever bucket its `tile_id` names.
307 pub fn push(&mut self, tile_id: u64, record: &[u8]) -> Result<()> {
308 if self.sealed {
309 return err("a sealed bucket set cannot be pushed to");
310 }
311 let i = self.index_of(tile_id)?;
312 if self.files[i].is_none() {
313 let f = File::create(&self.paths[i])
314 .map_err(|e| Error(format!("cannot create {}: {e}", self.paths[i].display())))?;
315 self.files[i] = Some(BufWriter::with_capacity(1 << 18, f));
316 }
317 let w = self.files[i].as_mut().expect("just opened");
318 w.write_all(record)
319 .map_err(|e| Error(format!("writing {}: {e}", self.paths[i].display())))?;
320 self.records[i] += 1;
321 self.bytes[i] += record.len() as u64;
322 self.pushed += 1;
323 self.pushed_bytes += record.len() as u64;
324 Ok(())
325 }
326
327 /// Flush every bucket and check the books.
328 ///
329 /// The push-time tallies, the file lengths and the set's totals must all agree.
330 /// This is `graph_build.rs`'s expected-count gate adapted to a partition: a bucket
331 /// that quietly lost records would produce an archive with holes in it and nothing
332 /// downstream could tell.
333 pub fn seal(&mut self) -> Result<()> {
334 for (i, slot) in self.files.iter_mut().enumerate() {
335 if let Some(w) = slot {
336 w.flush()
337 .map_err(|e| Error(format!("flushing {}: {e}", self.paths[i].display())))?;
338 }
339 *slot = None;
340 }
341 let mut records = 0u64;
342 let mut bytes = 0u64;
343 for i in 0..self.paths.len() {
344 records += self.records[i];
345 bytes += self.bytes[i];
346 let on_disk = match std::fs::metadata(&self.paths[i]) {
347 Ok(m) => m.len(),
348 Err(_) if self.records[i] == 0 => 0,
349 Err(e) => {
350 return err(format!("cannot stat {}: {e}", self.paths[i].display()));
351 }
352 };
353 if on_disk != self.bytes[i] {
354 return err(format!(
355 "{} is {on_disk} byte(s) on disk but {} were pushed to it",
356 self.paths[i].display(),
357 self.bytes[i]
358 ));
359 }
360 }
361 if records != self.pushed || bytes != self.pushed_bytes {
362 return err(format!(
363 "bucket totals are {records} record(s)/{bytes} byte(s) but {} record(s)/{} \
364 byte(s) were pushed",
365 self.pushed, self.pushed_bytes
366 ));
367 }
368 self.sealed = true;
369 Ok(())
370 }
371
372 /// A reader over bucket `i`, or `None` when it holds nothing.
373 ///
374 /// Only valid after [`BucketSet::seal`]: reading a bucket whose writer has not been
375 /// flushed would miss its tail.
376 pub fn reader(&self, i: usize) -> Result<Option<BucketReader>> {
377 if !self.sealed {
378 return err("a bucket set must be sealed before it is read");
379 }
380 if self.records[i] == 0 {
381 return Ok(None);
382 }
383 let (lo, hi) = self.range_of(i);
384 let f = File::open(&self.paths[i])
385 .map_err(|e| Error(format!("cannot read {}: {e}", self.paths[i].display())))?;
386 Ok(Some(BucketReader {
387 src: BufReader::with_capacity(1 << 18, f),
388 path: self.paths[i].clone(),
389 lo,
390 hi,
391 expect_records: self.records[i],
392 expect_bytes: self.bytes[i],
393 seen_records: 0,
394 seen_bytes: 0,
395 done: false,
396 buf: Vec::new(),
397 }))
398 }
399
400 /// Every record in bucket `i`, checked against the push-time tallies.
401 pub fn load(&self, i: usize) -> Result<Vec<SpillRecord>> {
402 let Some(mut r) = self.reader(i)? else { return Ok(Vec::new()) };
403 let mut out = Vec::with_capacity(self.records[i].min(1 << 22) as usize);
404 while let Some(rec) = r.next()? {
405 out.push(rec);
406 }
407 Ok(out)
408 }
409
410 /// Best-effort cleanup, also run on drop.
411 pub fn remove(&mut self) {
412 for slot in self.files.iter_mut() {
413 *slot = None;
414 }
415 for p in &self.paths {
416 let _ = std::fs::remove_file(p);
417 }
418 // Only if empty, so a shared spill directory survives.
419 let _ = std::fs::remove_dir(&self.dir);
420 }
421}
422
423impl Drop for BucketSet {
424 /// A zoom's buckets are a temporary, so their lifetime is the set's. Per-zoom spill
425 /// is the reason peak disk is the largest single zoom rather than the sum of them,
426 /// and that only holds if a dropped set really does take its files with it.
427 fn drop(&mut self) {
428 self.remove();
429 }
430}