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

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

overlay.rs304 lines · 12.0 KiBRaw
1//! `overlay` — build patch-overlay segments from two `.mamaps` archives.
2//!
3//! Phase 1 server generator: input is the old (base) and new packed
4//! archives, output is overlay segments only, never a rewritten base. Each
5//! segment is a small self-contained `.mamaps` file written by the existing
6//! [`StreamWriter`](crate::mamaps::write::StreamWriter) — same header,
7//! dictionary, root, leaves and body format as the base — holding only
8//! changed/added tile bodies with overlay-relative offsets. Deleted tiles
9//! are tombstone tile ids in the overlay descriptor, not bodies (a
10//! tombstone has no bytes to store).
11//!
12//! Insertion efficiency falls out of the layout: the base is never touched,
13//! so a mid-world insert appends one body to an overlay segment plus one
14//! overlay leaf entry. No base `offset_delta`, `base_data_offset`, sidecar
15//! offset or footer movement.
16//!
17//! Bodies travel through [`MamapsArchive::tile_bytes`] (decompressed raw)
18//! and back in through [`StreamWriter::append_encoded`] (re-compressed).
19//! DEFLATE is deterministic, so a body the new build wrote compresses to
20//! the same stored bytes here — the segment carries what the new archive
21//! carries, byte for byte.
22use crate::churn::{snapshot, FileReader, Snapshot};
23
24use tilecodec::stream::RangeReader;
25
26use crate::mamaps::archive::{unified_build_id, ArchiveView};
27use crate::mamaps::read::MamapsArchive;
28use crate::mamaps::write::Options;
29use crate::manifest::SEGMENT_CAP_BYTES;
30use crate::pmtiles::tile_zxy;
31use crate::proto::{err, Result};
32
33/// One tile the overlay must carry: its id and its new stored length (for
34/// segment packing); the bytes are fetched at emit time.
35#[derive(Debug, Clone, Copy)]
36pub struct Carry {
37 /// Tile id in the new archive.
38 pub tile_id: u64,
39 /// Stored body length in the new archive (compressed, if it says so).
40 pub length: u32,
41}
42
43/// The overlay plan: which new bodies ship, which old tiles are tombstoned,
44/// and how the bodies split into cap-sized segments.
45pub struct OverlayPlan {
46 /// New bodies to ship, ascending by tile id.
47 pub carries: Vec<Carry>,
48 /// Deleted tile ids (old-only), ascending. No bodies ship for these.
49 pub tombstones: Vec<u64>,
50 /// Segment boundaries as `carries` index ranges (each segment's stored
51 /// bodies fit [`SEGMENT_CAP_BYTES`]).
52 pub segments: Vec<(usize, usize)>,
53 /// `overlay_build_id` for every segment header + the manifest.
54 pub overlay_build_id: u64,
55 /// Zoom range + bbox + flags carried from the new archive's header.
56 pub header: SegmentHeader,
57}
58
59/// Header facts the segment writer needs from the new archive.
60#[derive(Debug, Clone, Copy)]
61pub struct SegmentHeader {
62 /// New archive's `build_id` (pinned in the manifest as the overlay source).
63 pub new_build_id: u64,
64 /// Base archive's `build_id` (compat pin).
65 pub base_build_id: u64,
66 /// New archive's zoom range (every carried tile is inside it).
67 pub min_zoom: u8,
68 /// New archive's zoom range.
69 pub max_zoom: u8,
70 /// New archive's bbox, carried so segments describe the same world.
71 pub bbox: (i32, i32, i32, i32),
72 /// Whether the new archive's rings are validated.
73 pub rings_validated: bool,
74}
75
76/// Diff two snapshots into an [`OverlayPlan`].
77///
78/// Interval merge over tile-id covers (both ascending): same tile + same
79/// fingerprint skips wholesale (a run re-split with identical bytes ships
80/// nothing — the overlay carries bodies, not index shapes). Same tile +
81/// different fingerprint, or new-only cover = carry. Old-only cover =
82/// tombstone. No per-tile expansion: planet's ~63M addressed tiles never
83/// materialise as a map.
84///
85/// Carries split greedily at [`SEGMENT_CAP_BYTES`] of stored bodies; the
86/// index overhead per segment is kilobytes against a 512 MiB cap. Carries
87/// may repeat a body (dedup-shared across tiles); the segment writer
88/// re-collapses those.
89pub fn plan(
90 old: &Snapshot,
91 new: &Snapshot,
92 old_archive: &MamapsArchive<impl RangeReader>,
93 new_archive: &MamapsArchive<impl RangeReader>,
94) -> OverlayPlan {
95 let mut carries: Vec<Carry> = Vec::new();
96 let mut tombstones: Vec<(u64, u64)> = Vec::new();
97 let (mut i, mut j) = (0usize, 0usize);
98 while i < old.entries.len() && j < new.entries.len() {
99 let a = &old.entries[i];
100 let b = &new.entries[j];
101 let (a0, a1) = (a.tile_id, a.tile_id + u64::from(a.run_length));
102 let (b0, b1) = (b.tile_id, b.tile_id + u64::from(b.run_length));
103 if a1 <= b0 {
104 tombstones.push((a0, a1));
105 i += 1;
106 } else if b1 <= a0 {
107 push_carry_range(&mut carries, b, b0, b1);
108 j += 1;
109 } else if a.hash == b.hash {
110 // Overlap with identical bytes: skip the overlap, advance the
111 // cover that ends first.
112 if a1 <= b1 {
113 i += 1;
114 }
115 if b1 <= a1 {
116 j += 1;
117 }
118 } else {
119 // Overlap with different bytes: the overlap carries the new body.
120 let (lo, hi) = (a0.max(b0), a1.min(b1));
121 push_carry_span(&mut carries, b, lo, hi);
122 if a1 <= b1 {
123 i += 1;
124 }
125 if b1 <= a1 {
126 j += 1;
127 }
128 }
129 }
130 for a in &old.entries[i..] {
131 tombstones.push((a.tile_id, a.tile_id + u64::from(a.run_length)));
132 }
133 for b in &new.entries[j..] {
134 push_carry_range(&mut carries, b, b.tile_id, b.tile_id + u64::from(b.run_length));
135 }
136 // Flatten tombstone ranges to ids (tombstones are rare: real deletes, not
137 // coverage edges — a coverage-edge tombstone storm means the wrong pair).
138 let mut tombstone_ids = Vec::new();
139 for (lo, hi) in tombstones {
140 tombstone_ids.extend(lo..hi);
141 }
142 let mut segments = Vec::new();
143 let mut start = 0usize;
144 let mut bytes = 0u64;
145 for (n, c) in carries.iter().enumerate() {
146 if n > start && bytes + u64::from(c.length) > SEGMENT_CAP_BYTES {
147 segments.push((start, n));
148 start = n;
149 bytes = 0;
150 }
151 bytes += u64::from(c.length);
152 }
153 if start < carries.len() || carries.is_empty() {
154 segments.push((start, carries.len()));
155 }
156 let new_hdr = &new_archive.header;
157 let overlay_build_id = unified_build_id(
158 b"overlay-v1",
159 &old_archive.header.build_id.to_le_bytes(),
160 &new_hdr.build_id.to_le_bytes(),
161 &[],
162 b"mamaps-overlay-v1",
163 );
164 OverlayPlan {
165 carries,
166 tombstones: tombstone_ids,
167 segments,
168 overlay_build_id,
169 header: SegmentHeader {
170 new_build_id: new_hdr.build_id,
171 base_build_id: old_archive.header.build_id,
172 min_zoom: new_hdr.min_zoom,
173 max_zoom: new_hdr.max_zoom,
174 bbox: (new_hdr.min_lon_e7, new_hdr.min_lat_e7, new_hdr.max_lon_e7, new_hdr.max_lat_e7),
175 rings_validated: new_hdr.rings_validated(),
176 },
177 }
178}
179
180/// Append one carry per tile of `[lo, hi)` (all inside one new entry, so one body).
181fn push_carry_span(carries: &mut Vec<Carry>, entry: &crate::churn::Entry, lo: u64, hi: u64) {
182 // One carry per tile: the body repeats per tile here (dedup-shared
183 // across tiles) and the segment writer re-collapses identical bodies.
184 for t in lo..hi {
185 carries.push(Carry { tile_id: t, length: entry.length });
186 }
187}
188
189/// Append carries for a whole new cover `[lo, hi)` known to be new-only.
190fn push_carry_range(carries: &mut Vec<Carry>, entry: &crate::churn::Entry, lo: u64, hi: u64) {
191 push_carry_span(carries, entry, lo, hi);
192}
193
194/// Emit one segment file: fetch each carried tile's raw body from the new
195/// archive and append it (ascending — carries are ascending by construction).
196pub fn emit_segment<R: RangeReader>(
197 new_archive: &MamapsArchive<R>,
198 plan: &OverlayPlan,
199 range: (usize, usize),
200 out: &std::path::Path,
201) -> Result<u64> {
202 let options = Options {
203 min_zoom: plan.header.min_zoom,
204 max_zoom: plan.header.max_zoom,
205 build_id: plan.overlay_build_id,
206 compress: true,
207 rings_validated: plan.header.rings_validated,
208 min_lon_e7: plan.header.bbox.0,
209 min_lat_e7: plan.header.bbox.1,
210 max_lon_e7: plan.header.bbox.2,
211 max_lat_e7: plan.header.bbox.3,
212 ..Options::default()
213 };
214 let mut writer = crate::mamaps::write::StreamWriter::new(options)?;
215 for carry in &plan.carries[range.0..range.1] {
216 let (z, x, y) = tile_zxy(carry.tile_id);
217 let Some(raw) = new_archive.tile_bytes(z, x as u32, y as u32)? else {
218 return err(format!(
219 "overlay carry tile {} vanished from the new archive",
220 carry.tile_id,
221 ));
222 };
223 writer.append_encoded(carry.tile_id, &raw)?;
224 }
225 writer.finish_to_path(out)?;
226 Ok(std::fs::metadata(out)
227 .map_err(|e| crate::proto::Error(format!("cannot stat {}: {e}", out.display())))?
228 .len())
229}
230
231/// A sidecar section payload sliced out of the new archive, for chunked
232/// section publishing (large kinds ship as files; the client skips
233/// unchanged chunks by hash).
234pub struct SectionPayload {
235 /// Archive kind id.
236 pub kind: u8,
237 /// Verbatim payload bytes from the new archive.
238 pub bytes: Vec<u8>,
239}
240
241/// Slice every sidecar section out of the new archive (tiles-only archives
242/// yield none). Payloads are verbatim — no re-encode, no re-compress.
243pub fn section_payloads(new_bytes_prefix_info: &NewArchiveSections) -> Vec<SectionPayload> {
244 new_bytes_prefix_info
245 .payloads
246 .iter()
247 .map(|(kind, bytes)| SectionPayload { kind: *kind, bytes: bytes.clone() })
248 .collect()
249}
250
251/// The new archive's sidecar sections, read whole (they stream at publish
252/// time; the generator box holds them transiently, like `mamaps_pack`).
253pub struct NewArchiveSections {
254 /// `(kind, payload bytes)` in kind order.
255 pub payloads: Vec<(u8, Vec<u8>)>,
256}
257
258/// Read a packed archive's sidecar payloads whole, validated by
259/// [`ArchiveView::parse`] (same checks the device loaders run).
260pub fn read_new_sections(path: &std::path::Path) -> Result<NewArchiveSections> {
261 let bytes = std::fs::read(path)
262 .map_err(|e| crate::proto::Error(format!("cannot read {}: {e}", path.display())))?;
263 let (header, _, _) = crate::mamaps::read::open_prefix(&bytes)?;
264 let view = ArchiveView::parse(&bytes, &header)?;
265 let mut payloads = Vec::with_capacity(view.entries.len());
266 for e in &view.entries {
267 payloads.push((e.kind, bytes[e.offset as usize..(e.offset + e.len) as usize].to_vec()));
268 }
269 Ok(NewArchiveSections { payloads })
270}
271
272/// Open both archives' tile indexes for planning + emitting.
273pub struct ArchivePair {
274 /// Base (old) archive over its file.
275 pub old_archive: MamapsArchive<FileReader>,
276 /// New archive over its file.
277 pub new_archive: MamapsArchive<FileReader>,
278 /// Base fingerprint snapshot.
279 pub old_snapshot: Snapshot,
280 /// New fingerprint snapshot.
281 pub new_snapshot: Snapshot,
282 /// Base file length (footer read).
283 pub old_len: u64,
284 /// New file length.
285 pub new_len: u64,
286}
287
288/// Snapshot + open both archives. Range-based (no whole-file reads) except
289/// through the fingerprint pass, which streams distinct bodies once.
290pub fn open_pair(before: &std::path::Path, after: &std::path::Path) -> Result<ArchivePair> {
291 let old_len = std::fs::metadata(before)
292 .map_err(|e| crate::proto::Error(format!("cannot stat {}: {e}", before.display())))?
293 .len();
294 let new_len = std::fs::metadata(after)
295 .map_err(|e| crate::proto::Error(format!("cannot stat {}: {e}", after.display())))?
296 .len();
297 let old_reader = FileReader::open(before)?;
298 let new_reader = FileReader::open(after)?;
299 let old_snapshot = snapshot(&old_reader, old_len)?;
300 let new_snapshot = snapshot(&new_reader, new_len)?;
301 let old_archive = MamapsArchive::open(FileReader::open(before)?)?;
302 let new_archive = MamapsArchive::open(FileReader::open(after)?)?;
303 Ok(ArchivePair { old_archive, new_archive, old_snapshot, new_snapshot, old_len, new_len })
304}