Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / tiler_part3_s2.rs
tiler_part3_s2.rs227 lines · 8.1 KiBRaw
| 1 | impl RangeQueues { |
| 2 | fn new(ranges: usize) -> std::sync::Arc<RangeQueues> { |
| 3 | std::sync::Arc::new(RangeQueues { |
| 4 | state: Mutex::new(RangeState { |
| 5 | queues: (0..ranges).map(|_| std::collections::VecDeque::new()).collect(), |
| 6 | finished: vec![false; ranges], |
| 7 | current: 0, |
| 8 | ahead: 0, |
| 9 | abandoned: false, |
| 10 | coordinator_waiting: false, |
| 11 | workers_waiting: 0, |
| 12 | }), |
| 13 | cv: std::sync::Condvar::new(), |
| 14 | }) |
| 15 | } |
| 16 | |
| 17 | /// Whether the coordinator has stopped reading (an earlier range failed). |
| 18 | fn abandoned(&self) -> bool { |
| 19 | self.state.lock().expect("the merge's range queues").abandoned |
| 20 | } |
| 21 | |
| 22 | /// Range `r`'s sending half, for its worker. Dropping it marks the range finished. |
| 23 | fn sender(self: &std::sync::Arc<Self>, r: usize) -> RangeTx { |
| 24 | RangeTx { queues: std::sync::Arc::clone(self), r, local: Default::default() } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | /// One range worker's end of [`RangeQueues`]: `send` in the shape of the channel it replaced. |
| 29 | struct RangeTx { |
| 30 | queues: std::sync::Arc<RangeQueues>, |
| 31 | r: usize, |
| 32 | /// Tiles merged but not yet queued, and their byte estimate: handed over |
| 33 | /// [`SEND_BATCH`] at a time, so 48 workers take the shared lock once per batch rather than |
| 34 | /// once per tile (per-tile sends had most range workers parked on that lock). |
| 35 | local: std::cell::RefCell<(Vec<(RangeOut, u64)>, u64)>, |
| 36 | } |
| 37 | |
| 38 | /// Tiles a range worker hands over per lock acquisition (or fewer, once [`SEND_BATCH_BYTES`] of |
| 39 | /// them are held). |
| 40 | const SEND_BATCH: usize = 64; |
| 41 | const SEND_BATCH_BYTES: u64 = 4 << 20; |
| 42 | |
| 43 | impl RangeTx { |
| 44 | /// Queue one tile (or error) for range `r`. `Err` when the coordinator is gone, which ends the |
| 45 | /// worker exactly as a dropped receiver did. |
| 46 | fn send(&self, item: RangeOut) -> std::result::Result<(), ()> { |
| 47 | let bytes = match &item { |
| 48 | Ok((_, layers)) => tile_bytes(layers), |
| 49 | Err(_) => 0, |
| 50 | }; |
| 51 | let failed = item.is_err(); |
| 52 | let full = { |
| 53 | let mut local = self.local.borrow_mut(); |
| 54 | local.0.push((item, bytes)); |
| 55 | local.1 += bytes; |
| 56 | failed || local.0.len() >= SEND_BATCH || local.1 >= SEND_BATCH_BYTES |
| 57 | }; |
| 58 | if full { |
| 59 | self.flush() |
| 60 | } else { |
| 61 | Ok(()) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// Hand the held tiles to the queue, waiting while the range is over its bound: the count |
| 66 | /// bound when it is the range being drained, the shared run-ahead allowance otherwise. |
| 67 | fn flush(&self) -> std::result::Result<(), ()> { |
| 68 | let (batch, bytes) = std::mem::take(&mut *self.local.borrow_mut()); |
| 69 | if batch.is_empty() { |
| 70 | return Ok(()); |
| 71 | } |
| 72 | let q = &self.queues; |
| 73 | let mut s = q.state.lock().expect("the merge's range queues"); |
| 74 | loop { |
| 75 | if s.abandoned { |
| 76 | return Err(()); |
| 77 | } |
| 78 | let wait = if self.r == s.current { |
| 79 | s.queues[self.r].len() >= RANGE_QUEUE_BOUND |
| 80 | } else { |
| 81 | // Always let a range queue its first batch, so a range is never blocked behind |
| 82 | // its own empty queue; past that, the shared allowance decides. |
| 83 | !s.queues[self.r].is_empty() && s.ahead + bytes > RANGE_AHEAD_BYTES |
| 84 | }; |
| 85 | if !wait { |
| 86 | break; |
| 87 | } |
| 88 | s.workers_waiting += 1; |
| 89 | s = q.cv.wait(s).expect("the merge's range queues"); |
| 90 | s.workers_waiting -= 1; |
| 91 | } |
| 92 | if self.r != s.current { |
| 93 | s.ahead += bytes; |
| 94 | } |
| 95 | s.queues[self.r].extend(batch); |
| 96 | let wake = self.r == s.current && s.coordinator_waiting; |
| 97 | drop(s); |
| 98 | if wake { |
| 99 | q.cv.notify_all(); |
| 100 | } |
| 101 | Ok(()) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | impl Drop for RangeTx { |
| 106 | fn drop(&mut self) { |
| 107 | // Whatever is still held goes out first; then the range is finished. A coordinator that |
| 108 | // has gone away refuses the flush, which is fine: nobody is reading. |
| 109 | let _ = self.flush(); |
| 110 | let q = &self.queues; |
| 111 | q.state.lock().expect("the merge's range queues").finished[self.r] = true; |
| 112 | q.cv.notify_all(); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// Ordered coordinator over range workers: an iterator yielding the serial |
| 117 | /// tile sequence. |
| 118 | /// |
| 119 | /// Ranges drain strictly in order (range 0 to exhaustion, then range 1, ...), |
| 120 | /// so the yielded sequence is tile-ascending regardless of completion order. |
| 121 | /// A range's error aborts the drain with the lowest-indexed failure: ranges |
| 122 | /// before it drained cleanly, so it is the earliest tile-ordered failure — |
| 123 | /// deterministic, like serial. |
| 124 | struct ParallelMerge { |
| 125 | queues: std::sync::Arc<RangeQueues>, |
| 126 | ranges: usize, |
| 127 | done: bool, |
| 128 | /// Tiles taken off the current range's queue in one go, handed out one per `next`. |
| 129 | local: std::collections::VecDeque<RangeOut>, |
| 130 | } |
| 131 | |
| 132 | impl ParallelMerge { |
| 133 | fn new(queues: std::sync::Arc<RangeQueues>) -> ParallelMerge { |
| 134 | let ranges = queues.state.lock().expect("the merge's range queues").queues.len(); |
| 135 | ParallelMerge { queues, ranges, done: false, local: std::collections::VecDeque::new() } |
| 136 | } |
| 137 | |
| 138 | /// Move everything queued for the current range into `local`, advancing past finished |
| 139 | /// ranges, waiting only when the current range has nothing yet. `false` once every range |
| 140 | /// has drained. |
| 141 | fn refill(&mut self) -> bool { |
| 142 | let q = &self.queues; |
| 143 | let mut s = q.state.lock().expect("the merge's range queues"); |
| 144 | loop { |
| 145 | if s.current >= self.ranges { |
| 146 | return false; |
| 147 | } |
| 148 | let current = s.current; |
| 149 | if !s.queues[current].is_empty() { |
| 150 | self.local.extend(s.queues[current].drain(..).map(|(item, _)| item)); |
| 151 | let wake = s.workers_waiting > 0; |
| 152 | drop(s); |
| 153 | if wake { |
| 154 | q.cv.notify_all(); |
| 155 | } |
| 156 | return true; |
| 157 | } |
| 158 | if s.finished[current] { |
| 159 | // Range drained cleanly: advance. Its successor's queued bytes stop counting |
| 160 | // against the run-ahead allowance now that it is the one being drained. |
| 161 | s.current += 1; |
| 162 | if s.current < self.ranges { |
| 163 | let next = s.current; |
| 164 | let queued: u64 = s.queues[next].iter().map(|(_, b)| *b).sum(); |
| 165 | s.ahead -= queued; |
| 166 | } |
| 167 | if s.workers_waiting > 0 { |
| 168 | q.cv.notify_all(); |
| 169 | } |
| 170 | continue; |
| 171 | } |
| 172 | s.coordinator_waiting = true; |
| 173 | s = q.cv.wait(s).expect("the merge's range queues"); |
| 174 | s.coordinator_waiting = false; |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | impl Drop for ParallelMerge { |
| 180 | /// Release any worker still parked on its queue: whatever ended the drain, nobody reads |
| 181 | /// further, and the workers' scope is waiting to join them. |
| 182 | fn drop(&mut self) { |
| 183 | self.queues.state.lock().expect("the merge's range queues").abandoned = true; |
| 184 | self.queues.cv.notify_all(); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | impl Iterator for ParallelMerge { |
| 189 | type Item = Result<(u64, Vec<ChunkEntry>)>; |
| 190 | |
| 191 | fn next(&mut self) -> Option<Result<(u64, Vec<ChunkEntry>)>> { |
| 192 | if self.done { |
| 193 | return None; |
| 194 | } |
| 195 | if self.local.is_empty() && !self.refill() { |
| 196 | self.done = true; |
| 197 | return None; |
| 198 | } |
| 199 | let item = self.local.pop_front().expect("refilled above"); |
| 200 | if item.is_err() { |
| 201 | // Lowest-indexed failure wins because lower ranges already drained clean; nothing |
| 202 | // further is read. |
| 203 | self.done = true; |
| 204 | self.local.clear(); |
| 205 | self.queues.state.lock().expect("the merge's range queues").abandoned = true; |
| 206 | self.queues.cv.notify_all(); |
| 207 | } |
| 208 | Some(item) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | enum MergeStream<'a> { |
| 213 | Serial(Merged<'a>), |
| 214 | Parallel(ParallelMerge), |
| 215 | } |
| 216 | |
| 217 | impl Iterator for MergeStream<'_> { |
| 218 | type Item = Result<(u64, Vec<ChunkEntry>)>; |
| 219 | |
| 220 | fn next(&mut self) -> Option<Result<(u64, Vec<ChunkEntry>)>> { |
| 221 | match self { |
| 222 | MergeStream::Serial(m) => m.next(), |
| 223 | MergeStream::Parallel(m) => m.next(), |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 |