Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / store_part3_s1.rs
store_part3_s1.rs276 lines · 11.1 KiBRaw
| 1 | impl WaySink { |
| 2 | #[cfg(test)] |
| 3 | pub fn create(path: &Path) -> Result<WaySink> { |
| 4 | let file = File::create(path) |
| 5 | .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; |
| 6 | Ok(WaySink { |
| 7 | // A megabyte, because the writes are a few dozen bytes each and there are millions. |
| 8 | out: WayOut::File(BufWriter::with_capacity(1 << 20, file)), |
| 9 | record: Vec::new(), |
| 10 | last_id: 0, |
| 11 | count: 0, |
| 12 | refs: 0, |
| 13 | max_ref: 0, |
| 14 | at: 0, |
| 15 | blocks: Vec::new(), |
| 16 | }) |
| 17 | } |
| 18 | |
| 19 | /// Anonymous twin of [`create`](Self::create): same records in pagefile-backed |
| 20 | /// memory, no file. `path` names nothing — it only rides |
| 21 | /// along for error messages. Pair with [`WaySink::finish_anon`]. |
| 22 | #[cfg(test)] |
| 23 | pub fn create_anon(path: &Path) -> Result<WaySink> { |
| 24 | Self::create_planned(path, osm_ingest::mem::SpillPlan::Anon) |
| 25 | } |
| 26 | |
| 27 | /// Create with an explicit staging plan. See [`Sink::create_planned`]: the budget gate picks |
| 28 | /// `File` when anon commit does not fit, and `File` stages through the `.tmp` at `path`, |
| 29 | /// removed after materialise like every other scratch file. Pair with |
| 30 | /// [`finish_either`](Self::finish_either). |
| 31 | pub fn create_planned(path: &Path, plan: osm_ingest::mem::SpillPlan) -> Result<WaySink> { |
| 32 | let out = match plan { |
| 33 | osm_ingest::mem::SpillPlan::Anon => { |
| 34 | WayOut::Anon(tile_build::anon::AnonStore::new()) |
| 35 | } |
| 36 | osm_ingest::mem::SpillPlan::File => { |
| 37 | eprintln!(" [stage A] ways spill -> {} (file backend: commit budget)", path.display()); |
| 38 | let file = File::create(path) |
| 39 | .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; |
| 40 | // A megabyte, because the writes are a few dozen bytes each and there are millions. |
| 41 | WayOut::File(BufWriter::with_capacity(1 << 20, file)) |
| 42 | } |
| 43 | }; |
| 44 | Ok(WaySink { |
| 45 | out, |
| 46 | record: Vec::new(), |
| 47 | last_id: 0, |
| 48 | count: 0, |
| 49 | refs: 0, |
| 50 | max_ref: 0, |
| 51 | at: 0, |
| 52 | blocks: Vec::new(), |
| 53 | }) |
| 54 | } |
| 55 | |
| 56 | /// Append one classified way. `id` must be greater than the previous call's. |
| 57 | /// |
| 58 | /// `name` is the display label for `places`/`poi` ways, `None` for every other layer. Written |
| 59 | /// as a length-prefixed string per record — zero bytes for the nameless, which is nearly all |
| 60 | /// of them. `lane_count`, `turn_fwd`, `turn_bwd` and `carriageway` are a road's lane count, |
| 61 | /// per-lane turn masks and directional split, empty for every other layer and for a road with |
| 62 | /// no lane tags; a handful of trailing varints per record, which the scratch file (removed |
| 63 | /// after materialise) affords. |
| 64 | #[allow(clippy::too_many_arguments)] |
| 65 | #[cfg(test)] |
| 66 | pub fn push( |
| 67 | &mut self, |
| 68 | id: i64, |
| 69 | class: &Class, |
| 70 | refs: &[i64], |
| 71 | name: Option<&str>, |
| 72 | lane_count: u8, |
| 73 | turn_fwd: &[u16], |
| 74 | turn_bwd: &[u16], |
| 75 | carriageway: Carriageway, |
| 76 | building: Option<BuildingAttrs>, |
| 77 | ) -> Result<()> { |
| 78 | if self.count > 0 && id <= self.last_id { |
| 79 | return err(unsorted_ways(id, self.last_id)); |
| 80 | } |
| 81 | self.record.clear(); |
| 82 | put_svarint(&mut self.record, id.wrapping_sub(self.last_id)); |
| 83 | let max_ref = encode_way_tail( |
| 84 | &mut self.record, |
| 85 | class, |
| 86 | refs, |
| 87 | name, |
| 88 | lane_count, |
| 89 | turn_fwd, |
| 90 | turn_bwd, |
| 91 | carriageway, |
| 92 | building, |
| 93 | )?; |
| 94 | self.max_ref = self.max_ref.max(max_ref); |
| 95 | // Moved out rather than cloned: `out_write` takes `&mut self`, so `&self.record` |
| 96 | // cannot borrow across the call, and a per-way clone is a memcpy per record over |
| 97 | // millions of records. The buffer is restored below with its capacity intact, so the |
| 98 | // `clear` at the top of the next `push` still reuses the allocation. |
| 99 | let record = std::mem::take(&mut self.record); |
| 100 | let result = self.out_write(&record).map_err(|e| { |
| 101 | Error(format!("cannot write the ways spill: {e}")) |
| 102 | }); |
| 103 | let len = record.len() as u64; |
| 104 | self.record = record; |
| 105 | result?; |
| 106 | self.note_block(len, 1); |
| 107 | self.last_id = id; |
| 108 | self.count += 1; |
| 109 | self.refs += refs.len() as u64; |
| 110 | Ok(()) |
| 111 | } |
| 112 | |
| 113 | /// Append a run of ways a worker encoded ([`WayBlock`]). Writes exactly what `push` would |
| 114 | /// have written for those ways one at a time: the block's first id varint is re-encoded |
| 115 | /// against the last id this sink saw, the rest is copied verbatim. The ordering rule is |
| 116 | /// enforced across the block boundary just as `push` enforces it between records. |
| 117 | pub fn push_block(&mut self, block: &WayBlock) -> Result<()> { |
| 118 | if block.count == 0 { |
| 119 | return Ok(()); |
| 120 | } |
| 121 | if self.count > 0 && block.first_id <= self.last_id { |
| 122 | return err(unsorted_ways(block.first_id, self.last_id)); |
| 123 | } |
| 124 | self.record.clear(); |
| 125 | put_svarint(&mut self.record, block.first_id.wrapping_sub(self.last_id)); |
| 126 | let head = std::mem::take(&mut self.record); |
| 127 | let wrote = self |
| 128 | .out_write(&head) |
| 129 | .and_then(|()| self.out_write(&block.bytes[block.head_len..])); |
| 130 | let len = (head.len() + block.bytes.len() - block.head_len) as u64; |
| 131 | self.record = head; |
| 132 | wrote?; |
| 133 | self.note_block(len, block.count); |
| 134 | self.last_id = block.last_id; |
| 135 | self.count += block.count; |
| 136 | self.refs += block.refs; |
| 137 | self.max_ref = self.max_ref.max(block.max_ref); |
| 138 | Ok(()) |
| 139 | } |
| 140 | |
| 141 | /// Index `len` bytes / `ways` records just written at `self.at`, whose first delta is taken |
| 142 | /// from `self.last_id` (still the pre-write value). Coalesced into the previous entry while |
| 143 | /// that stays within [`WAY_BLOCK_WAYS`]: a run of consecutive records decodes from the first |
| 144 | /// one's base however it was written, so merging entries changes nothing but the index size. |
| 145 | fn note_block(&mut self, len: u64, ways: u64) { |
| 146 | match self.blocks.last_mut() { |
| 147 | Some(last) if last.offset + last.len == self.at && last.ways + ways <= WAY_BLOCK_WAYS => { |
| 148 | last.len += len; |
| 149 | last.ways += ways; |
| 150 | } |
| 151 | _ => self.blocks.push(WayBlockLoc { |
| 152 | offset: self.at, |
| 153 | len, |
| 154 | start_last_id: self.last_id, |
| 155 | ways, |
| 156 | }), |
| 157 | } |
| 158 | self.at += len; |
| 159 | } |
| 160 | |
| 161 | fn out_write(&mut self, bytes: &[u8]) -> Result<()> { |
| 162 | match &mut self.out { |
| 163 | WayOut::File(f) => f.write_all(bytes).map_err(|e| { |
| 164 | Error(format!("cannot write the ways spill: {e}")) |
| 165 | }), |
| 166 | WayOut::Anon(a) => a.push(bytes).map(|_| ()).map_err(|e| { |
| 167 | Error(format!("cannot stage the ways spill: {e}")) |
| 168 | }), |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /// Flush, and report how many ways were written, how many node refs they hold between them, and |
| 173 | /// the largest of those refs. |
| 174 | /// |
| 175 | /// None of the three is a statistic. [`crate::extract`] reads this file back to collect the node |
| 176 | /// ids pass 3 must resolve, and it picks between two ways of doing that on the ref count: below a |
| 177 | /// budget it sizes one exact vector (grown by extension a 200 M-id vector doubles into 2.1 GB of |
| 178 | /// capacity, and the realloc that gets it there holds the old and new allocations at once), and |
| 179 | /// above it sizes a bitset from `max_ref`. Both numbers are free here, where every ref is already |
| 180 | /// being walked to encode it, and neither is recoverable later without a second pass. |
| 181 | #[cfg(test)] |
| 182 | pub fn finish(mut self) -> Result<WayCounts> { |
| 183 | match &mut self.out { |
| 184 | WayOut::File(f) => f.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?, |
| 185 | WayOut::Anon(a) => a.finish(), |
| 186 | } |
| 187 | Ok(WayCounts { |
| 188 | ways: self.count, |
| 189 | refs: self.refs, |
| 190 | max_ref: self.max_ref, |
| 191 | blocks: std::mem::take(&mut self.blocks), |
| 192 | }) |
| 193 | } |
| 194 | |
| 195 | /// Anonymous twin of [`finish`](Self::finish): seals the pagefile-backed |
| 196 | /// spill and hands back the counts plus the staged store. Errors on a |
| 197 | /// file-backed sink. |
| 198 | #[cfg(test)] |
| 199 | pub fn finish_anon(mut self) -> Result<(WayCounts, tile_build::anon::AnonStore)> { |
| 200 | match &mut self.out { |
| 201 | WayOut::File(_) => { |
| 202 | return err("finish_anon on a file-backed ways sink".to_string()) |
| 203 | } |
| 204 | WayOut::Anon(a) => a.finish(), |
| 205 | } |
| 206 | let counts = WayCounts { |
| 207 | ways: self.count, |
| 208 | refs: self.refs, |
| 209 | max_ref: self.max_ref, |
| 210 | blocks: std::mem::take(&mut self.blocks), |
| 211 | }; |
| 212 | match self.out { |
| 213 | WayOut::Anon(a) => Ok((counts, a)), |
| 214 | WayOut::File(_) => unreachable!("checked above"), |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | /// Seal, and hand back the counts plus the staged bytes on the anon plan or `None` on the |
| 219 | /// file plan (whose bytes live at the path the sink was created with). Unifies |
| 220 | /// [`finish`](Self::finish) and [`finish_anon`](Self::finish_anon) so callers that pick the |
| 221 | /// backend by budget seal without knowing which one they chose. |
| 222 | pub fn finish_either(mut self) -> Result<(WayCounts, Option<tile_build::anon::AnonStore>)> { |
| 223 | match &mut self.out { |
| 224 | WayOut::File(f) => f.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?, |
| 225 | WayOut::Anon(a) => a.finish(), |
| 226 | } |
| 227 | let counts = WayCounts { |
| 228 | ways: self.count, |
| 229 | refs: self.refs, |
| 230 | max_ref: self.max_ref, |
| 231 | blocks: std::mem::take(&mut self.blocks), |
| 232 | }; |
| 233 | match self.out { |
| 234 | WayOut::Anon(a) => Ok((counts, Some(a))), |
| 235 | WayOut::File(_) => Ok((counts, None)), |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | /// What a finished [`WaySink`] holds. |
| 241 | pub struct WayCounts { |
| 242 | pub ways: u64, |
| 243 | /// Node refs summed over every way, duplicates included — a capacity, not a cardinality. |
| 244 | pub refs: u64, |
| 245 | /// The largest node ref written, or zero if none were. What a bitset over the id space is sized |
| 246 | /// from. |
| 247 | pub max_ref: i64, |
| 248 | /// The block index over the stream, in stream order: what [`WayBlocks`] decodes from. |
| 249 | pub blocks: Vec<WayBlockLoc>, |
| 250 | } |
| 251 | |
| 252 | /// Reads back what a [`WaySink`] wrote, in the order it was written. |
| 253 | /// |
| 254 | /// File-backed ([`open`](Self::open)) or anonymous ([`open_anon`](Self::open_anon)): |
| 255 | /// the record format is a sequential varint stream either way, so the reader is |
| 256 | /// a cursor over bytes — a file cursor or a store offset. Same records, same order. |
| 257 | pub struct WayReader { |
| 258 | inner: WayIn, |
| 259 | last_id: i64, |
| 260 | seen: u64, |
| 261 | } |
| 262 | |
| 263 | /// Where a [`WayReader`] reads from. |
| 264 | enum WayIn { |
| 265 | #[cfg(test)] |
| 266 | File(BufReader<File>), |
| 267 | #[cfg(test)] |
| 268 | Anon { |
| 269 | store: std::sync::Arc<tile_build::anon::AnonStore>, |
| 270 | at: u64, |
| 271 | buf: Vec<u8>, |
| 272 | used: usize, |
| 273 | }, |
| 274 | /// One block of the stream, read whole ([`WayBlocks::reader`]). |
| 275 | Slice { buf: Vec<u8>, used: usize }, |
| 276 | } |