library:map: bring remote loader to MapLibre parity (#815)
- Commit
e0ad01b9eb0efafbebdc626d2fdc3202df2f5faf- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-14 17:43 UTC (1 month ago)
- Parents
f49d648
Diff
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 57c3f1eeec..cf07f19642 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -102,6 +102,11 @@ zxing = "3.5.4" libphonenumber = "9.0.38" litertlmAndroid = "0.14.0" brotli = "0.1.2"+# Pooled HTTP for :library:network's range-fetch path (issue 815): connection+# reuse + HTTP/2 multiplexing at MapLibre's 20/host concurrency, which per-request+# HttpURLConnection cannot give. 4.x for minSdk 21+ without the 5.x Kotlin-stdlib+# jump; grpc-okhttp pulls its own tree, so this is pinned independently.+okhttp = "4.12.0" # Standalone library from the AGP toolchain (com.android.tools.build), not the plugin — # :appstore uses it at runtime to verify APK source stamps. apksig = "8.7.3"@@ -302,6 +307,7 @@ zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" } libphonenumber = { module = "com.googlecode.libphonenumber:libphonenumber", version.ref = "libphonenumber" } litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", version.ref = "litertlmAndroid" } brotli-dec = { module = "org.brotli:dec", version.ref = "brotli" }+okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } apksig = { module = "com.android.tools.build:apksig", version.ref = "apksig" } # =============================================================================
library/map/src/main/rust/src/bridge/frame.rs
diff --git a/library/map/src/main/rust/src/bridge/frame.rs b/library/map/src/main/rust/src/bridge/frame.rsindex 6e77e0b04b..3c37fd81e6 100644--- a/library/map/src/main/rust/src/bridge/frame.rs+++ b/library/map/src/main/rust/src/bridge/frame.rs@@ -84,6 +84,10 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( // The drain sample below still records (zero elapsed on Moon frames) so the // frame-time rollup keeps its shape. let drain_start = std::time::Instant::now();+ // Finished tiles that scrolled out while in flight, skipped before upload (issue 815).+ // Declared outside the Moon guard so the per-frame report below can cite it; Moon frames+ // skip the drain and leave it zero.+ let mut stale_dropped = 0usize; if crate::camera::moon_active(&camera) { // No selection runs for the Moon, so no zoom is recorded — and the Earth set // resumes mid-stream when the body switches back, which deserves the burst path.@@ -96,6 +100,29 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( break; }; map.in_flight.remove(&key);+ // Scrolled out while in flight (issue 815): the bytes are real but nobody looks at this+ // tile anymore, so it skips the upload slot — visible tiles drain first. Absent/failed+ // bookkeeping below still runs (an absence is a fact whatever the viewport), only the+ // Vulkan upload is spared. Disabled until the first Earth frame selects a set.+ if !map.last_visible.is_empty() && !map.last_visible.contains(&key) {+ stale_dropped += 1;+ match result {+ TileResult::Ready(_) => {+ map.retry.remove(&key);+ }+ TileResult::Absent => {+ map.absent.insert(key);+ map.retry.remove(&key);+ }+ TileResult::Failed => {+ let attempts = map.retry.get(&key).map_or(0, |(n, _)| *n).saturating_add(1);+ let wait = std::time::Duration::from_millis(retry_delay_ms(attempts));+ map.retry+ .insert(key, (attempts, std::time::Instant::now() + wait));+ }+ }+ continue;+ } match result { TileResult::Ready(mesh) => { uploads += 1;@@ -207,7 +234,38 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( } else { Vec::new() };- for tile in visible.iter().chain(wash_extra.iter()) {+ // The wanted set for the drain-and-replace generation (issue 815): when it changes, the+ // queued remainder of the previous set is stale and is drained below, so a pan does not+ // wait behind fetches for tiles that scrolled out. `wash_extra` counts as wanted — it is+ // enqueued through the same gates.+ let wanted_keys: std::collections::HashSet<u64> = visible+ .iter()+ .chain(wash_extra.iter())+ .map(|t| t.key())+ .collect();+ // Drain-and-replace, Earth frames only: the Moon guard below leaves the Earth queue+ // untouched so switching back resumes mid-stream. `try_lock` never blocks — a worker+ // parked in `recv` holds the lock, and blocking behind it would deadlock the render+ // thread against its own send — so a contended frame skips the drain and the normal gates+ // below still dedup. Drained keys leave `in_flight` and are re-sent when still wanted;+ // keys a worker already took stay marked and are never duplicated. Skipped while the+ // wanted set is steady (the common case) and before the first Earth frame.+ let moon = crate::camera::moon_active(&camera);+ if !moon && !map.last_visible.is_empty() && wanted_keys != map.last_visible {+ if let Ok(queue) = map.wanted_queue.try_lock() {+ let mut drained = 0usize;+ while let Ok(tile) = queue.try_recv() {+ map.in_flight.remove(&tile.key());+ drained += 1;+ }+ if drained > 0 {+ log_info(&format!("queue generation changed: drained {drained} stale tiles"));+ }+ }+ }+ // Centre-first enqueue (issue 815): the middle of the screen fills before the edges, so a+ // cold pan shows something useful as early as possible instead of scan order.+ for tile in center_first(&visible).iter().chain(wash_extra.iter()) { let key = tile.key(); if map.renderer.has_tile(key, generation) || map.absent.contains(&key)@@ -232,11 +290,12 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( // Skipped on Moon frames along with the fetch above: `visible` is empty, and // retaining against it would drop every Earth backoff (harmless but wasteful) // — worse, `retain` below with an empty keep would EVICT the Earth set. The- // Moon guard keeps both calls out.- let moon = crate::camera::moon_active(&camera);+ // Moon guard keeps all three out, and `last_visible` keeps the Earth set it+ // resumes against. if !moon { map.retry.retain_visible(&visible); map.renderer.retain(&keep, &visible, RESIDENT_TILE_CAP);+ map.last_visible = wanted_keys; } map.renderer .step_times@@ -279,7 +338,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( let steps = map.renderer.step_times.borrow_mut().report(1); log_info(&format!( "z{:.2} @{:.4},{:.4} b{:.0} vp {}x{}dp {}x{}px msaa {}x | resident {} tiles, {} meshes, \- {} draws, {} tris | {} in flight, {} absent | archive z{}..{} | {}",+ {} draws, {} tris | {} in flight, {} absent, {} stale-dropped | archive z{}..{} | {}", camera.zoom, camera.center_lon, camera.center_lat,@@ -295,6 +354,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( triangles, map.in_flight.len(), map.absent.len(),+ stale_dropped, min_zoom, max_zoom, steps,@@ -309,6 +369,30 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( } } +/// The wanted tiles nearest the viewport centre first.+///+/// A cold pan shows its middle before its edges: the centre tile is what the user is looking+/// at, and scan order would spend the first fetches on a corner. Sorts by squared distance to+/// the set's own mean, which is the viewport centre for a coverage box. A handful of tiles, so+/// the sort is noise next to one fetch.+fn center_first(visible: &[select::TileId]) -> Vec<select::TileId> {+ if visible.len() < 2 {+ return visible.to_vec();+ }+ let (sx, sy) = visible+ .iter()+ .fold((0i64, 0i64), |(sx, sy), t| (sx + t.x as i64, sy + t.y as i64));+ let n = visible.len() as i64;+ let (cx, cy) = (sx / n, sy / n);+ let mut out = visible.to_vec();+ out.sort_by_key(|t| {+ let dx = t.x as i64 - cx;+ let dy = t.y as i64 - cy;+ dx * dx + dy * dy+ });+ out+}+ /// The last frame's per-step times in nanos, in [`Step::ALL`](crate::timing::Step) order. /// /// For the debug overlay's slow poll (~2–4 Hz): a copy, so the render thread never blocks on it.
library/map/src/main/rust/src/bridge/handle.rs
diff --git a/library/map/src/main/rust/src/bridge/handle.rs b/library/map/src/main/rust/src/bridge/handle.rsindex c9a31a3f18..40e2834bb3 100644--- a/library/map/src/main/rust/src/bridge/handle.rs+++ b/library/map/src/main/rust/src/bridge/handle.rs@@ -8,7 +8,7 @@ use crate::vulkan::renderer::Renderer; use jni::sys::jlong; use std::collections::{HashMap, HashSet}; use std::sync::mpsc::{Receiver, Sender};-use std::sync::Arc;+use std::sync::{Arc, Mutex}; /// The archive's zoom range, shared with the worker that reads it out of the header. /// /// Atomics rather than a `Mutex` because `render` reads this every frame, and it must be@@ -66,8 +66,13 @@ impl ZoomRange { /// body — so its cost is dominated by round-trip latency, not CPU. One worker serialises /// every tile behind every other: the archive probe measured a 24-tile screenful taking ~15 /// seconds that way, which is exactly the "really slow to change which elements load"-/// symptom. Four overlaps the waiting without opening enough sockets to matter.-pub(crate) const WORKER_COUNT: usize = 4;+/// symptom.+///+/// Eight is the first step toward MapLibre's 20 concurrent requests per host (issue 815):+/// it halves the serial waves of a cold screenful while staying inside what a phone's cores+/// and radio handle without thermal or socket pressure. Raise toward 20 only with the+/// per-tile `queue/fetch/tess` logs showing fetch still dominating and thermals clean.+pub(crate) const WORKER_COUNT: usize = 8; /// The most tiles allowed resident on the GPU at once. ///@@ -94,14 +99,17 @@ pub(crate) const RESIDENT_TILE_CAP: usize = 64; /// the tile is not re-requested, because its key is only removed from `in_flight` once it is /// actually drained. ///-/// Four is a deliberate middle: a screenful is a couple of dozen tiles, so a cold pan fills in-/// over roughly ten frames, which is a fraction of the fetch and decode latency that preceded it-/// and so is not visible. Lower would start to look like a trickle; higher gives the tail back.+/// Eight is the middle that moved with the worker count (issue 815): a screenful is a+/// couple of dozen tiles, so a cold pan fills in over roughly half the frames it did at+/// four workers and four uploads, which stays a fraction of the fetch and decode latency+/// that preceded it and so is not visible. Lower would start to look like a trickle now that+/// twice as many workers finish per frame; higher gives the frame-time tail back — an upload+/// is still around a hundred `vkAllocateMemory` calls on the Choreographer callback. /// /// Raised after a zoom-out (see [`upload_budget`]): a zoom-out invalidates a screenful at once,-/// and draining it at four per frame leaves the map coarse for seconds while the ancestors it+/// and draining it at the steady rate leaves the map coarse for seconds while the ancestors it /// needs are already finished and waiting in the channel.-pub(crate) const UPLOADS_PER_FRAME: usize = 4;+pub(crate) const UPLOADS_PER_FRAME: usize = 8; /// Uploads per frame while the camera is zooming out: the burst rate that drains a screenful /// of newly-visible ancestors in a frame or two rather than ten.@@ -145,6 +153,25 @@ pub(crate) struct MapHandle { pub(crate) finished: Receiver<(u64, TileResult)>, /// Tiles the workers should fetch. pub(crate) wanted: Sender<TileId>,+ /// The receiving end of [`wanted`](Self::wanted), shared with the workers.+ ///+ /// Lets a frame drain tiles that stopped being wanted *before* a worker spends a fetch on+ /// them (issue 815): panning queues the new viewport behind the old one, and without a+ /// drain the new area waits behind fetches nobody looks at anymore. Drained keys leave+ /// `in_flight` (see `frame.rs`), so still-visible ones are re-sent through the normal gates+ /// and genuinely-fetching workers are never disturbed — only never-started queue entries go+ /// away. Locked with `try_lock`, never blocking: a worker parked in `recv` holds it, and+ /// blocking behind that worker would deadlock the render thread against its own send.+ pub(crate) wanted_queue: Arc<Mutex<Receiver<TileId>>>,+ /// The wanted tile keys of the last Earth frame, for the drain-and-replace generation.+ ///+ /// When the wanted set changes, the queued (never-started) remainder of the previous set is+ /// stale and is drained (see [`wanted_queue`](Self::wanted_queue)); when it matches, the+ /// queue flows untouched. Finished tiles outside this set skip uploading: they scrolled out+ /// while in flight, and spending an upload slot on them only delays visible tiles. Empty+ /// before the first Earth frame, which disables the stale-drop until there is a set to be+ /// stale against. Untouched on Moon frames, so the Earth set resumes mid-stream.+ pub(crate) last_visible: HashSet<u64>, /// Requested but not yet arrived, so a tile is not asked for sixty times a second /// while it is in flight. pub(crate) in_flight: HashSet<u64>,
library/map/src/main/rust/src/bridge/lifecycle.rs
diff --git a/library/map/src/main/rust/src/bridge/lifecycle.rs b/library/map/src/main/rust/src/bridge/lifecycle.rsindex d827e41d2c..319f55f109 100644--- a/library/map/src/main/rust/src/bridge/lifecycle.rs+++ b/library/map/src/main/rust/src/bridge/lifecycle.rs@@ -108,6 +108,9 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( // worker). See `spawn_worker`. let header = Arc::new(std::sync::OnceLock::new()); let prefix_gate = Arc::new(std::sync::atomic::AtomicBool::new(false));+ // One parsed-leaf cache shared by every worker's archive view (issue 815): a cold leaf is+ // fetched once per surface, not once per worker.+ let leaves = Arc::new(tilecodec::mamaps::read::LeafCache::new()); for index in 0..WORKER_COUNT { spawn_worker( index,@@ -121,6 +124,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( toggles.clone(), header.clone(), prefix_gate.clone(),+ leaves.clone(), ); } @@ -129,6 +133,8 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( layers: style::layers(), finished: finished_rx, wanted: wanted_tx,+ wanted_queue: queue.clone(),+ last_visible: HashSet::new(), in_flight: HashSet::new(), absent: AbsentSet::new(), retry: RetryMap::new(),
library/map/src/main/rust/src/bridge/workers.rs
diff --git a/library/map/src/main/rust/src/bridge/workers.rs b/library/map/src/main/rust/src/bridge/workers.rsindex eb3a664fed..93c008057d 100644--- a/library/map/src/main/rust/src/bridge/workers.rs+++ b/library/map/src/main/rust/src/bridge/workers.rs@@ -14,22 +14,28 @@ use crate::tile::source::{ use std::sync::mpsc::{Receiver, Sender}; use std::sync::{Arc, Mutex}; use tilecodec::mamaps::header::Header;+use tilecodec::mamaps::read::LeafCache; use tilecodec::mamaps::MamapsArchive; use tilecodec::stream::RangeReader; use tilecodec::stream::OPEN_PREFIX_BYTES; /// A worker: opens its own view of the archive, then serves tile requests until the queue /// closes. ///-/// Each worker holds its **own** [`MamapsArchive`] (and its own leaf-index cache and prefix-/// parse — small CPU work on an in-memory prefix), so its range reads need no lock. What is-/// shared across the surface's workers is everything that costs a *network round trip*: the-/// header `build_id` fetch (one JNI request per cold start, not one per worker, via `header`)-/// and the forced first-read revalidation (one prefix read, not one per worker, via-/// `prefix_gate`). The on-disk range cache is shared too, and is safe to share because every-/// entry is written temp-then-renamed.+/// Each worker holds its **own** [`MamapsArchive`] view (and its own prefix parse — small CPU+/// work on an in-memory prefix), so its range reads need no lock, but every view of one+/// surface reads parsed leaves through the **shared** [`LeafCache`]: a cold leaf is fetched+/// once no matter how many workers' tiles need it. What is shared across the surface's+/// workers is everything that costs a *network round trip*: the header `build_id` fetch (one+/// JNI request per cold start, not one per worker, via `header`) and the forced first-read+/// revalidation (one prefix read, not one per worker, via `prefix_gate`). The on-disk range+/// cache is shared too, and is safe to share because every entry is written temp-then-renamed. ///-/// `header`/`prefix_gate` are built once per surface in `lifecycle::create` and handed to every-/// worker: whichever worker arrives first does the fetch while the rest block on it.+/// header`/`prefix_gate` are built once per surface in `lifecycle::create` and handed to every+/// worker: whichever worker arrives first does the fetch while the rest block on it. `leaves`+/// is the surface's shared parsed-leaf cache (issue 815): every worker's archive reads through+/// it, so a cold leaf is fetched once no matter how many workers' tiles need it — previously+/// each worker carried a private cache and one viewport's leaves were fetched up to once per+/// worker. #[allow(clippy::too_many_arguments)] pub(crate) fn spawn_worker( index: usize,@@ -43,6 +49,7 @@ pub(crate) fn spawn_worker( toggles: Arc<SharedToggles>, header: Arc<std::sync::OnceLock<Option<u64>>>, prefix_gate: Arc<std::sync::atomic::AtomicBool>,+ leaves: Arc<LeafCache>, ) { let started = std::thread::Builder::new() .name(format!("map-tiles-{index}"))@@ -62,7 +69,7 @@ pub(crate) fn spawn_worker( return; } };- match MamapsArchive::open(reader) {+ match MamapsArchive::open_with_cache(reader, Arc::clone(&leaves)) { Ok(archive) => { serve(index, archive, &queue, &finished, &zoom_range, &toggles) }@@ -99,7 +106,7 @@ pub(crate) fn spawn_worker( ); reader.set_online(online.get()); - let archive = match MamapsArchive::open(reader) {+ let archive = match MamapsArchive::open_with_cache(reader, Arc::clone(&leaves)) { Ok(a) => a, Err(e) => { log(&format!(@@ -183,7 +190,7 @@ fn fetch_header_with_retry(archive_url: &str) -> Option<u64> { /// is opened differs, never how tiles are served from it. fn serve<R: RangeReader>( index: usize,- mut archive: MamapsArchive<R>,+ archive: MamapsArchive<R>, queue: &Arc<Mutex<Receiver<TileId>>>, finished: &Sender<(u64, TileResult)>, zoom_range: &Arc<ZoomRange>,
library/map/src/main/rust/src/tile/cache.rs
diff --git a/library/map/src/main/rust/src/tile/cache.rs b/library/map/src/main/rust/src/tile/cache.rsindex 93a9d4a8bf..893c3c571f 100644--- a/library/map/src/main/rust/src/tile/cache.rs+++ b/library/map/src/main/rust/src/tile/cache.rs@@ -53,8 +53,20 @@ pub struct RangeCache { max_bytes: u64, /// Injectable so the freshness and eviction policies are testable without sleeping. clock: Box<dyn Fn() -> u64 + Send + Sync>,+ /// Writes since the last eviction scan (issue 815).+ ///+ /// [`evict_if_over_cap`](Self::evict_if_over_cap) stats every entry in the directory, so+ /// running it per write during a cold fill — dozens of ranges per screenful across 8 workers —+ /// spends more syscalls on the scan than on the writes. Eviction is best-effort anyway (a full+ /// disk must not stop the map), so the scan runs every [`EVICT_EVERY_WRITES`] writes; the+ /// cache overshoots its cap by at most that many entries in between.+ writes_since_evict: std::sync::atomic::AtomicU64, } +/// How many writes accumulate between eviction scans. A screenful is dozens of ranges, so the+/// scan runs about once per screenful rather than once per range.+const EVICT_EVERY_WRITES: u64 = 32;+ impl RangeCache { /// Open the cache once with the full origin marker, dropping every entry /// when the marker differs from the one on disk.@@ -78,6 +90,7 @@ impl RangeCache { dir, max_bytes, clock,+ writes_since_evict: std::sync::atomic::AtomicU64::new(0), }; cache.invalidate_on_origin_change(origin); cache@@ -136,7 +149,16 @@ impl RangeCache { if self.write_inner(key, body).is_err() { return; }- self.evict_if_over_cap();+ if self+ .writes_since_evict+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed)+ + 1+ >= EVICT_EVERY_WRITES+ {+ self.writes_since_evict+ .store(0, std::sync::atomic::Ordering::Relaxed);+ self.evict_if_over_cap();+ } } fn write_inner(&self, key: &str, body: &[u8]) -> std::io::Result<()> {@@ -467,7 +489,9 @@ mod tests { let f = Fixture::new("evict"); let clock = Arc::new(AtomicU64::new(1_000_000)); let cache = cache_with(&f.dir, clock.clone(), 1000);- for i in 0..10 {+ // A multiple of the eviction batch threshold (issue 815: the scan runs every 32 writes,+ // not per write), so the scan runs on the last write and the cap holds at the end.+ for i in 0..64 { cache.write(&RangeCache::key(URL, &format!("bytes={i}")), &[0u8; 200]); // Distinct mtimes, so eviction order is well defined. std::thread::sleep(std::time::Duration::from_millis(12));@@ -480,7 +504,24 @@ mod tests { // Evicts to a margin below the cap, not exactly to it. assert!(total <= 800, "evicts with headroom: {total}"); // The most recent write survives; the oldest does not.- assert!(cache.read(&RangeCache::key(URL, "bytes=9")).is_some());+ assert!(cache.read(&RangeCache::key(URL, "bytes=63")).is_some()); assert!(cache.read(&RangeCache::key(URL, "bytes=0")).is_none()); }++ #[test]+ fn eviction_waits_for_a_batch_of_writes() {+ // The scan stats the whole directory, so it runs every 32 writes rather than per write+ // (issue 815). Below the threshold nothing is evicted even over the cap.+ let f = Fixture::new("evict_batch");+ let clock = Arc::new(AtomicU64::new(1_000_000));+ let cache = cache_with(&f.dir, clock.clone(), 100);+ for i in 0..10 {+ cache.write(&RangeCache::key(URL, &format!("bytes={i}")), &[0u8; 200]);+ }+ let total: u64 = data_files(&f.dir)+ .iter()+ .map(|p| fs::metadata(p).unwrap().len())+ .sum();+ assert_eq!(total, 2000, "under the batch threshold no scan runs yet");+ } }
library/map/src/main/rust/src/tile/geometry/tests_extra6.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra6.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra6.rsindex 10080b014a..9fe0ed5f90 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_extra6.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra6.rs@@ -169,7 +169,7 @@ fn a_tile_read_out_of_a_mamaps_archive_tessellates() { writer.append(id, &real()).expect("append"); let bytes = writer.finish().expect("finish"); - let mut archive = MamapsArchive::open(Memory {+ let archive = MamapsArchive::open(Memory { bytes, requests: RefCell::new(0), })
library/network/build.gradle.kts
diff --git a/library/network/build.gradle.kts b/library/network/build.gradle.ktsindex 58770dcc4b..366c0f2aae 100644--- a/library/network/build.gradle.kts+++ b/library/network/build.gradle.kts@@ -3,8 +3,12 @@ plugins { } dependencies {- // Android-only networking – HttpURLConnection + own WS, no OkHttp/Ktor.+ // Android-only networking – HttpURLConnection + own WS for most paths; pooled OkHttp+ // behind NetworkClient.execute only (issue 815 range fetches). implementation(libs.kotlinx.serialization.json) implementation(libs.brotli.dec) // manual br decoding – keep catalog entry implementation(libs.kotlinx.coroutines.android)+ // Pooled engine for NetworkClient.execute (issue 815): connection reuse + HTTP/2 at+ // MapLibre's 20/host concurrency for the JNI range-fetch path. Nothing else moves.+ implementation(libs.okhttp) }
library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.ktindex 1a28fea3f2..becbbcf1c4 100644--- a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt+++ b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt@@ -129,6 +129,15 @@ object NetworkClient { var defaultSslSocketFactory: SSLSocketFactory? = null private set + /**+ * The trust manager behind [defaultSslSocketFactory], retained because pooled clients+ * (OkHttp, issue 815) need the manager alongside the factory at construction time.+ * Null exactly when the factory is null (SYSTEM trust).+ */+ @Volatile+ var defaultTrustManager: javax.net.ssl.X509TrustManager? = null+ private set+ @Volatile var currentBundle: TrustBundle = TrustBundle.SYSTEM private set@@ -159,11 +168,13 @@ object NetworkClient { currentBundle = bundle if (bundle == TrustBundle.SYSTEM) { defaultSslSocketFactory = null+ defaultTrustManager = null Log.status(TAG, "Initialized with SYSTEM bundle (platform default trust)") return } val result = BundledTrust.createFactory(appCtx, bundle) defaultSslSocketFactory = result?.first+ defaultTrustManager = result?.second if (defaultSslSocketFactory == null) { Log.status(TAG, "Bundle $bundle produced no factory (missing DERs?), falling back to system trust") } else {@@ -174,6 +185,9 @@ object NetworkClient { @Synchronized fun initWithFactory(factory: SSLSocketFactory?, bundle: TrustBundle = TrustBundle.SYSTEM) { defaultSslSocketFactory = factory+ // A bare factory without its manager cannot back a pooled client; the pool falls back+ // to system trust until init() supplies the pair.+ defaultTrustManager = null currentBundle = bundle initialized = true }@@ -272,6 +286,10 @@ object NetworkClient { * optional redirect suppression. Does not throw on 4xx/5xx — inspect * [RawResponse.status]. *+ * Served by the pooled OkHttp engine ([PooledHttpEngine], issue 815) unless its kill-switch+ * is off or the call pins a bare factory the pool cannot share — both fall back to the+ * historical `HttpURLConnection` path with identical semantics.+ * * [sslSocketFactory] pins the TLS trust anchors for this call (Signal uses * a factory built over its bundled root); null keeps the platform default or * the bundle default set via [init]. Use [useSystemTrust]=true to force system@@ -288,6 +306,12 @@ object NetworkClient { sslSocketFactory: SSLSocketFactory? = null, useSystemTrust: Boolean = false, ): RawResponse {+ if (PooledHttpEngine.USE_POOLED_ENGINE && PooledHttpEngine.canServe(sslSocketFactory)) {+ return PooledHttpEngine.execute(+ url, method, headers, body, followRedirects,+ connectTimeoutMs, readTimeoutMs, useSystemTrust,+ )+ } val r = HttpUrlEngine.internalExecute( url, method, headers, HttpUrlEngine.toBodyBytes(body), followRedirects, connectTimeoutMs, readTimeoutMs,
library/network/src/main/java/com/vayunmathur/library/network/PooledHttpEngine.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/PooledHttpEngine.kt b/library/network/src/main/java/com/vayunmathur/library/network/PooledHttpEngine.ktnew file mode 100644index 0000000000..4fc2e35654--- /dev/null+++ b/library/network/src/main/java/com/vayunmathur/library/network/PooledHttpEngine.kt@@ -0,0 +1,226 @@+package com.vayunmathur.library.network++import java.io.IOException+import java.util.concurrent.TimeUnit+import javax.net.ssl.SSLSocketFactory+import javax.net.ssl.X509TrustManager+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import okhttp3.ConnectionPool+import okhttp3.Dispatcher+import okhttp3.MediaType.Companion.toMediaTypeOrNull+import okhttp3.OkHttpClient+import okhttp3.Protocol+import okhttp3.Request+import okhttp3.RequestBody.Companion.toRequestBody++/**+ * Pooled HTTP engine behind [NetworkClient.execute] (issue 815).+ *+ * MapLibre parity for the range-fetch path: [HttpUrlEngine] opens a fresh `HttpURLConnection`+ * per request with no pool or HTTP/2 config, so a cold screenful of tiles pays a TLS handshake+ * per range. This keeps one shared `OkHttpClient` — connection pool, HTTP/2 multiplexing, and+ * `Dispatcher.maxRequestsPerHost = 20` matching MapLibre's `HttpRequestImpl` — so the second+ * range reuses the first's connection.+ *+ * Scope is deliberately narrow: only `execute` (the JNI bridge's range fetches, image+ * fetching, traffic/street-view reads) moves here. `performRequest`, `stream`,+ * `performRequestInputStream` and the JSON path stay on [HttpUrlEngine], whose redirect,+ * decompression and streaming semantics they depend on. Redirects *are* followed here+ * (OkHttp default), and the final URL is reported like `execute` always did.+ *+ * TLS never leaves `:library:network`: the client is built once per trust state from the same+ * [BundledTrust] pair `init` installed, and rebuilt when `init` changes the bundle. A per-call+ * [SSLSocketFactory] without its manager cannot back a pooled client, so explicit factories+ * fall back to [HttpUrlEngine] rather than partitioning the pool per connection.+ *+ * Synchronous `suspend` shape, like the engine it replaces: the JNI bridge calls through+ * `runBlocking`, so this must not change threading — OkHttp's own dispatcher threads do the+ * I/O inside the blocking `execute()` call, which runs on `Dispatchers.IO`.+ */+internal object PooledHttpEngine {++ /**+ * MapLibre's per-host concurrency (`DEFAULT_MAXIMUM_CONCURRENT_REQUESTS`, OkHttp+ * `Dispatcher.setMaxRequestsPerHost(20)`): enough that a screenful of ranges overlaps+ * instead of serialising, few enough to stay inside a radio's happy place.+ */+ const val MAX_REQUESTS_PER_HOST = 20++ /** Range fetches are small and latency-bound; fail fast rather than hang a tile worker. */+ private const val CONNECT_TIMEOUT_SECONDS = 10L+ private const val READ_TIMEOUT_SECONDS = 30L++ /** Pooled connections idle out after a minute; the pool holds a handful per host. */+ private const val KEEP_ALIVE_MINUTES = 1L+ private const val MAX_IDLE_CONNECTIONS = 10++ /** Set while [USE_POOLED_ENGINE] routes `execute` here; cleared by the fallback path. */+ @Volatile+ var lastUsedPooled = false+ private set++ /**+ * Kill-switch for the rollout (issue 815): true routes [NetworkClient.execute] through the+ * pool, false keeps the historical [HttpUrlEngine] path. One release with the flag, then the+ * old path goes.+ */+ @Volatile+ var USE_POOLED_ENGINE = true++ private val lock = Any()++ @Volatile+ private var client: OkHttpClient? = null++ /** Same, but with redirects disabled for callers that inspect 3xx themselves. */+ @Volatile+ private var noRedirectClient: OkHttpClient? = null++ /** The trust state [client] was built for; a mismatch rebuilds it (see [clientFor]). */+ @Volatile+ private var builtFactory: SSLSocketFactory? = null++ @Volatile+ private var builtManager: X509TrustManager? = null++ @Volatile+ private var builtSystemTrust = false++ /**+ * Whether this engine can serve a call with [explicitFactory]: only when it is null (use the+ * client's trust) — a bare factory without its manager cannot join the pool.+ */+ fun canServe(explicitFactory: SSLSocketFactory?): Boolean = explicitFactory == null++ suspend fun execute(+ url: String,+ method: String,+ headers: Map<String, *>,+ body: Any?,+ followRedirects: Boolean,+ connectTimeoutMs: Long?,+ readTimeoutMs: Long? = connectTimeoutMs,+ useSystemTrust: Boolean,+ ): RawResponse = withContext(Dispatchers.IO) {+ val client = clientFor(useSystemTrust, followRedirects)+ val bodyBytes = HttpUrlEngine.toBodyBytes(body)+ val builder = Request.Builder().url(url)+ applyHeaders(builder, headers)+ // OkHttp (unlike HttpURLConnection) requires POST/PUT/PATCH to carry a body object even+ // when empty; every current `execute` caller is a GET, but a null must not become a crash.+ val requestBody = bodyBytes?.toRequestBody(null, 0, bodyBytes.size)+ ?: if (method == "POST" || method == "PUT" || method == "PATCH") {+ ByteArray(0).toRequestBody(null, 0, 0)+ } else {+ null+ }+ builder.method(method, requestBody)+ val call = client.newCall(builder.build())+ // try-with-resources equivalent: `use` closes the response (and its body) on every path.+ call.execute().use { response ->+ val bytes = try {+ response.body?.bytes() ?: ByteArray(0)+ } catch (e: IOException) {+ throw IOException("Failed to read response body from $url", e)+ }+ val respHeaders = mutableMapOf<String, List<String>>()+ for (name in response.headers.names()) {+ respHeaders[name] = response.headers.values(name)+ }+ // Redirects were followed by the client when asked; otherwise 3xx answers here as a+ // normal response and the caller inspects status, exactly like HttpURLConnection.+ val finalUrl = response.request.url.toString()+ lastUsedPooled = true+ RawResponse(+ response.code,+ response.message,+ bytes,+ respHeaders,+ finalUrl,+ )+ }+ }++ private fun applyHeaders(builder: Request.Builder, headers: Map<String, *>) {+ headers.forEach { (k, v) ->+ when (v) {+ is Iterable<*> -> v.forEach { elem ->+ if (elem != null) builder.addHeader(k, elem.toString())+ }+ else -> if (v != null) builder.header(k, v.toString())+ }+ }+ }++ /**+ * The shared client for [useSystemTrust] and [followRedirects], rebuilding when `init`+ * changed the trust state underneath it. SYSTEM trust (or no bundled factory) builds a plain+ * client; otherwise the bundled factory + manager are pinned once at construction so every+ * connection shares one pool instead of partitioning it per request. Redirect-following is a+ * client-level setting in OkHttp, so the suppressing caller gets its own shared instance+ * rather than a per-call build.+ */+ private fun clientFor(useSystemTrust: Boolean, followRedirects: Boolean): OkHttpClient {+ val factory = if (useSystemTrust) null else NetworkClient.defaultSslSocketFactory+ val manager = if (useSystemTrust) null else NetworkClient.defaultTrustManager+ synchronized(lock) {+ if (followRedirects) {+ val current = client+ if (current != null && factory === builtFactory && manager === builtManager &&+ useSystemTrust == builtSystemTrust+ ) {+ return current+ }+ val built = buildClient(factory, manager, true)+ client = built+ builtFactory = factory+ builtManager = manager+ builtSystemTrust = useSystemTrust+ return built+ }+ noRedirectClient?.let { return it }+ val built = buildClient(factory, manager, false)+ noRedirectClient = built+ return built+ }+ }++ private fun buildClient(+ factory: SSLSocketFactory?,+ manager: X509TrustManager?,+ followRedirects: Boolean,+ ): OkHttpClient {+ val dispatcher = Dispatcher().apply {+ maxRequestsPerHost = MAX_REQUESTS_PER_HOST+ }+ val pool = ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_MINUTES, TimeUnit.MINUTES)+ val builder = OkHttpClient.Builder()+ .dispatcher(dispatcher)+ .connectionPool(pool)+ .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))+ .followRedirects(followRedirects)+ .connectTimeout(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS)+ .readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)+ if (factory != null && manager != null) {+ builder.sslSocketFactory(factory, manager)+ }+ return builder.build()+ }++ /** Test seam: drop the cached client so the next call rebuilds from current trust state. */+ internal fun resetForTests() {+ synchronized(lock) {+ client?.dispatcher?.executorService?.shutdown()+ client?.connectionPool?.evictAll()+ noRedirectClient?.dispatcher?.executorService?.shutdown()+ noRedirectClient?.connectionPool?.evictAll()+ client = null+ noRedirectClient = null+ builtFactory = null+ builtManager = null+ builtSystemTrust = false+ lastUsedPooled = false+ }+ }+}
library/network/src/test/java/com/vayunmathur/library/network/PooledHttpEngineTest.kt
diff --git a/library/network/src/test/java/com/vayunmathur/library/network/PooledHttpEngineTest.kt b/library/network/src/test/java/com/vayunmathur/library/network/PooledHttpEngineTest.ktnew file mode 100644index 0000000000..a3fb31b100--- /dev/null+++ b/library/network/src/test/java/com/vayunmathur/library/network/PooledHttpEngineTest.kt@@ -0,0 +1,107 @@+package com.vayunmathur.library.network++import com.sun.net.httpserver.HttpServer+import java.net.InetSocketAddress+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking++/**+ * Covers [PooledHttpEngine], the pooled OkHttp transport behind [NetworkClient.execute]+ * (issue 815). A JDK in-process server keeps this hermetic — no network, no extra test+ * dependency. Only routing, mapping and redirect semantics are asserted here; connection+ * reuse itself is verified on device through the per-range timing logs.+ */+class PooledHttpEngineTest {++ private lateinit var server: HttpServer+ private var baseUrl = ""++ @BeforeTest+ fun setUp() {+ PooledHttpEngine.USE_POOLED_ENGINE = true+ PooledHttpEngine.resetForTests()+ server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+ baseUrl = "http://127.0.0.1:${server.address.port}"+ server.start()+ }++ @AfterTest+ fun tearDown() {+ server.stop(0)+ PooledHttpEngine.USE_POOLED_ENGINE = true+ PooledHttpEngine.resetForTests()+ }++ @Test+ fun range_request_maps_status_headers_and_body() = runBlocking {+ val body = ByteArray(4096) { (it % 251).toByte() }+ server.createContext("/range") { exchange ->+ val range = exchange.requestHeaders.getFirst("Range")+ assertEquals("bytes=0-127", range)+ exchange.responseHeaders.add("Content-Range", "bytes 0-127/4096")+ exchange.sendResponseHeaders(206, 128)+ exchange.responseBody.use { it.write(body, 0, 128) }+ }+ val response = NetworkClient.execute(+ url = "$baseUrl/range",+ headers = mapOf("Range" to "bytes=0-127"),+ )+ assertEquals(206, response.status)+ assertContentEquals(body.copyOf(128), response.bytes)+ assertEquals(listOf("bytes 0-127/4096"), response.headerValues("Content-Range"))+ assertTrue(PooledHttpEngine.lastUsedPooled, "execute routes through the pool")+ }++ @Test+ fun redirects_are_followed_and_final_url_reported() = runBlocking {+ server.createContext("/old") { exchange ->+ exchange.responseHeaders.add("Location", "$baseUrl/new")+ exchange.sendResponseHeaders(302, -1)+ exchange.close()+ }+ server.createContext("/new") { exchange ->+ val body = "arrived".toByteArray()+ exchange.sendResponseHeaders(200, body.size.toLong())+ exchange.responseBody.use { it.write(body) }+ }+ val response = NetworkClient.execute(url = "$baseUrl/old")+ assertEquals(200, response.status)+ assertEquals("arrived", response.text)+ assertEquals("$baseUrl/new", response.url)+ }++ @Test+ fun kill_switch_off_keeps_the_historical_path() = runBlocking {+ PooledHttpEngine.USE_POOLED_ENGINE = false+ server.createContext("/plain") { exchange ->+ val body = "legacy".toByteArray()+ exchange.sendResponseHeaders(200, body.size.toLong())+ exchange.responseBody.use { it.write(body) }+ }+ val response = NetworkClient.execute(url = "$baseUrl/plain")+ assertEquals(200, response.status)+ assertEquals("legacy", response.text)+ assertFalse(PooledHttpEngine.lastUsedPooled, "kill-switch off bypasses the pool")+ }++ @Test+ fun an_explicit_factory_cannot_join_the_pool() {+ assertTrue(PooledHttpEngine.canServe(null), "default trust joins the pool")+ val factory = javax.net.ssl.SSLSocketFactory.getDefault() as javax.net.ssl.SSLSocketFactory+ assertFalse(+ PooledHttpEngine.canServe(factory),+ "a bare factory without its manager falls back instead of partitioning the pool",+ )+ }++ @Test+ fun per_host_concurrency_matches_maplibre() {+ assertEquals(20, PooledHttpEngine.MAX_REQUESTS_PER_HOST)+ }+}
library/tilecodec/src/main/rust/src/mamaps/read.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read.rs b/library/tilecodec/src/main/rust/src/mamaps/read.rsindex d4efe9e8f1..1d9979050b 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read.rs@@ -24,6 +24,7 @@ pub mod archive; pub mod helpers;+pub mod leaf_cache; // Private imports mirroring the original single-file module, so tests' `use super::*` // keeps resolving the same names. Pure moves; nothing here changed.@@ -54,3 +55,4 @@ use std::cell::RefCell; pub use archive::MamapsArchive; pub use helpers::{decompress, open_prefix, read_all, MIN_FILE_LEN};+pub use leaf_cache::{LeafCache, DEFAULT_LEAF_CACHE_CAPACITY};
library/tilecodec/src/main/rust/src/mamaps/read/archive.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rsindex 12827db116..afc3fe3e17 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs@@ -1,4 +1,5 @@ use super::helpers::decompress;+use super::leaf_cache::LeafCache; use crate::mamaps::body::Body; use crate::mamaps::dict::Dictionary; use crate::mamaps::header::Header;@@ -6,12 +7,20 @@ use crate::mamaps::index::{LeafEntry, RootEntry, self}; use crate::pmtiles::tile_id; use crate::proto::{Error, Result, err}; use crate::stream::{OPEN_PREFIX_BYTES, RangeReader};--/// How many parsed leaves to keep. Sixteen: a viewport walks a contiguous stretch-/// of the tile curve, so a small MRU covers panning without re-fetching.-const MAX_CACHED_LEAVES: usize = 16;+use std::sync::Arc; /// An open archive.+///+/// The parsed-leaf cache is shared across every reader of one archive: open+/// each worker's view with+/// [`open_with_cache`](MamapsArchive::open_with_cache) over the same+/// [`LeafCache`], and a cold leaf is fetched once no matter how many tiles+/// need it. That is the MapLibre-parity half of issue 815 — with a private+/// cache per worker, four workers covering one viewport fetched the same cold+/// leaves up to four times.+///+/// [`open`](MamapsArchive::open) keeps the old shape — a private cache — for+/// single-reader tools and tests, where sharing buys nothing. pub struct MamapsArchive<R: RangeReader> { /// Reachable from the crate so the request-counting tests in [`super`] can assert on the /// number of round trips, which is the contract this whole layout exists to hold.@@ -19,8 +28,7 @@ pub struct MamapsArchive<R: RangeReader> { pub header: Header, pub dictionary: Dictionary, root: Vec<RootEntry>,- /// `(leaf offset, entries)`, most-recently-used last.- leaves: Vec<(u64, Vec<LeafEntry>)>,+ leaves: Arc<LeafCache>, } impl<R: RangeReader> MamapsArchive<R> {@@ -37,7 +45,21 @@ impl<R: RangeReader> MamapsArchive<R> { /// writer asserts the budget, so a file that misses it was not written by this codec, and /// silently paying an extra round trip per open is exactly the cost the layout exists to /// avoid.+ ///+ /// The archive gets a private leaf cache. Readers that should share one —+ /// a surface's tile workers — want+ /// [`open_with_cache`](MamapsArchive::open_with_cache) instead. pub fn open(reader: R) -> Result<MamapsArchive<R>> {+ Self::open_with_cache(reader, Arc::new(LeafCache::new()))+ }++ /// [`open`](MamapsArchive::open) over a caller-supplied leaf cache.+ ///+ /// Every archive opened over the same [`LeafCache`] shares parsed leaves:+ /// the first worker to need a cold leaf fetches, inflates and parses it,+ /// and the rest take the cached copy. Thread-safe — `tile` and+ /// `tile_bytes` take `&self` — so one cache serves a whole surface.+ pub fn open_with_cache(reader: R, leaves: Arc<LeafCache>) -> Result<MamapsArchive<R>> { let prefix = reader.read(0, OPEN_PREFIX_BYTES)?; let header = Header::parse(&prefix)?; let section = |offset: u64, len: u64, what: &str| -> Result<&[u8]> {@@ -65,20 +87,20 @@ impl<R: RangeReader> MamapsArchive<R> { root.len(), )); }- Ok(MamapsArchive { reader, header, dictionary, root, leaves: Vec::new() })+ Ok(MamapsArchive { reader, header, dictionary, root, leaves }) } /// The decoded body for a tile, or `None` when the archive does not hold it. /// /// `None` rather than an error: most of a coastal viewport is off the edge of coverage, and /// that is the ordinary answer rather than a fault.- pub fn tile(&mut self, z: u8, x: u32, y: u32) -> Result<Option<Body>> {+ pub fn tile(&self, z: u8, x: u32, y: u32) -> Result<Option<Body>> { let Some(bytes) = self.tile_bytes(z, x, y)? else { return Ok(None) }; Ok(Some(Body::parse(&bytes)?)) } /// The decompressed body bytes for a tile, undecoded.- pub fn tile_bytes(&mut self, z: u8, x: u32, y: u32) -> Result<Option<Vec<u8>>> {+ pub fn tile_bytes(&self, z: u8, x: u32, y: u32) -> Result<Option<Vec<u8>>> { if z < self.header.min_zoom || z > self.header.max_zoom || z >= 32 { return Ok(None); }@@ -104,19 +126,16 @@ impl<R: RangeReader> MamapsArchive<R> { Ok(Some(decompress(self.header.compression, &stored)?)) } - /// The parsed leaf a root entry addresses, from the cache or over the wire.+ /// The parsed leaf a root entry addresses, from the shared cache or over the wire. /// /// A stored leaf is one raw-DEFLATE frame; it inflates whole to exactly /// `leaf_entry_count * 16` bytes and then binary-searches in memory like a raw leaf always- /// did. The request count is unchanged: one range read per cold leaf, whatever it stores.- fn leaf(&mut self, root: &RootEntry) -> Result<Vec<LeafEntry>> {- if let Some(position) = self.leaves.iter().position(|(offset, _)| *offset == root.leaf_offset)- {- // Move to the back: most-recently-used last.- let hit = self.leaves.remove(position);- let entries = hit.1.clone();- self.leaves.push(hit);- return Ok(entries);+ /// did. The request count is unchanged: one range read per cold leaf, whatever it stores —+ /// but now one per cold leaf *per cache*, not per reader, because the+ /// fetch happens outside the cache lock and the first copy published wins.+ fn leaf(&self, root: &RootEntry) -> Result<Arc<Vec<LeafEntry>>> {+ if let Some(hit) = self.leaves.get(root.leaf_offset) {+ return Ok(hit); } let raw_len = root.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64; let stored_len = if root.stored_len == 0 { raw_len } else { root.stored_len as u64 };@@ -144,11 +163,7 @@ impl<R: RangeReader> MamapsArchive<R> { index::decompress_leaf(&stored, raw_len)? }; let entries = index::parse_leaf(&raw)?;- if self.leaves.len() >= MAX_CACHED_LEAVES {- self.leaves.remove(0);- }- self.leaves.push((root.leaf_offset, entries.clone()));- Ok(entries)+ Ok(self.leaves.insert(root.leaf_offset, entries)) } /// A read that must come back at its full length.
library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs b/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rsnew file mode 100644index 0000000000..8dac26d234--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs@@ -0,0 +1,128 @@+//! A parsed-leaf cache shared by every reader of one archive.+//!+//! MapLibre parity (issue 815): MapLibre's `PMTilesFileSource` funnels every tile+//! through one actor holding a shared directory cache (up to 100 entries), so a+//! leaf is fetched once no matter how many tiles need it. Previously each+//! `MamapsArchive` carried a private 16-leaf MRU, so four tile workers covering+//! one viewport fetched and inflated the same cold leaves up to four times.+//!+//! Sharing is by `Arc<LeafCache>`: the entries are immutable once parsed, so a+//! hit is one lock, one `HashMap` lookup and one `Arc` clone — no 64 KB `Vec`+//! copy per tile, and no I/O under the lock on the hot path. Only a miss does+//! I/O, and it happens *outside* the lock: the caller fetches, inflates and+//! parses, then publishes with [`LeafCache::insert`], which keeps the first+//! copy when two workers race on the same cold leaf.++use std::collections::{HashMap, VecDeque};+use std::sync::{Arc, Mutex};++use crate::mamaps::index::LeafEntry;++/// How many parsed leaves a shared cache keeps by default.+///+/// Sixteen covered a viewport's walk when each worker had its own cache; shared+/// across all of a surface's workers the working set is the same leaves, so 64+/// leaves address 262 144 tiles — several screenfuls plus panning headroom —+/// while each entry stays a parsed in-memory index (tens of KB), not tile data.+pub const DEFAULT_LEAF_CACHE_CAPACITY: usize = 64;++struct State {+ entries: HashMap<u64, Arc<Vec<LeafEntry>>>,+ /// `leaf_offset`s in use order, most-recently-used last.+ order: VecDeque<u64>,+}++/// Parsed `.mamaps` leaves keyed by `leaf_offset`, shared across threads.+///+/// `Send + Sync` via interior mutability; construct once per surface and hand+/// an `Arc` clone to every `MamapsArchive` with+/// [`MamapsArchive::open_with_cache`](super::archive::MamapsArchive::open_with_cache).+/// A poisoned lock degrades to a miss (or a dropped insert), never a panic, so+/// a failed worker cannot wedge the rest of the surface.+pub struct LeafCache {+ capacity: usize,+ state: Mutex<State>,+}++impl LeafCache {+ /// A cache with [`DEFAULT_LEAF_CACHE_CAPACITY`] entries.+ pub fn new() -> Self {+ Self::with_capacity(DEFAULT_LEAF_CACHE_CAPACITY)+ }++ /// A cache with `capacity` entries. A zero capacity is raised to one.+ pub fn with_capacity(capacity: usize) -> Self {+ LeafCache {+ capacity: capacity.max(1),+ state: Mutex::new(State {+ entries: HashMap::new(),+ order: VecDeque::new(),+ }),+ }+ }++ /// The entry budget this cache was built with.+ pub fn capacity(&self) -> usize {+ self.capacity+ }++ /// How many leaves are currently cached.+ pub fn len(&self) -> usize {+ self.state.lock().map(|s| s.entries.len()).unwrap_or(0)+ }++ /// Whether the cache currently holds no leaf.+ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }++ /// The parsed leaf at `leaf_offset`, promoted to most-recently-used.+ ///+ /// `None` on a miss — or when the lock is poisoned, which is treated as a+ /// miss so readers fall back to fetching rather than failing.+ pub fn get(&self, leaf_offset: u64) -> Option<Arc<Vec<LeafEntry>>> {+ let mut state = self.state.lock().ok()?;+ let entries = state.entries.get(&leaf_offset)?.clone();+ if state.order.back() != Some(&leaf_offset) {+ state.order.retain(|o| *o != leaf_offset);+ state.order.push_back(leaf_offset);+ }+ Some(entries)+ }++ /// Publish a parsed leaf, evicting least-recently-used entries past capacity.+ ///+ /// Returns the stored handle. When two workers race on the same cold leaf+ /// the first copy wins and the loser is dropped, so the cache never holds+ /// two copies of one leaf.+ pub fn insert(&self, leaf_offset: u64, entries: Vec<LeafEntry>) -> Arc<Vec<LeafEntry>> {+ let mut state = match self.state.lock() {+ Ok(s) => s,+ // Publish failed: hand the caller its own copy so the tile still resolves.+ Err(_) => return Arc::new(entries),+ };+ if let Some(existing) = state.entries.get(&leaf_offset) {+ let existing = existing.clone();+ state.order.retain(|o| *o != leaf_offset);+ state.order.push_back(leaf_offset);+ return existing;+ }+ let stored = Arc::new(entries);+ state.entries.insert(leaf_offset, Arc::clone(&stored));+ state.order.push_back(leaf_offset);+ while state.entries.len() > self.capacity {+ if let Some(oldest) = state.order.pop_front() {+ state.entries.remove(&oldest);+ } else {+ break;+ }+ }+ stored+ }+}++impl Default for LeafCache {+ fn default() -> Self {+ Self::new()+ }+}
library/tilecodec/src/main/rust/tests/shared_leaf_cache.rs
diff --git a/library/tilecodec/src/main/rust/tests/shared_leaf_cache.rs b/library/tilecodec/src/main/rust/tests/shared_leaf_cache.rsnew file mode 100644index 0000000000..cea13cc943--- /dev/null+++ b/library/tilecodec/src/main/rust/tests/shared_leaf_cache.rs@@ -0,0 +1,198 @@+//! Shared leaf cache: the issue-815 MapLibre-parity gate.+//!+//! The lib test target is broken at HEAD by in-progress header work (`shared_*`+//! fields referenced from `mamaps::archive::tests` before they land on+//! `Header`), so like `leaf_compression.rs` this exercises the public API only:+//! it builds against the lib, never against `#[cfg(test)]` code.++use std::sync::Arc;+use tilecodec::mamaps::index::LeafEntry;+use tilecodec::mamaps::read::{LeafCache, DEFAULT_LEAF_CACHE_CAPACITY};++fn leaf(first: u32) -> Vec<LeafEntry> {+ vec![LeafEntry {+ tile_id_lo: first,+ run_length: 1,+ offset_delta: 0,+ length: 8,+ }]+}++#[test]+fn an_inserted_leaf_reads_back() {+ let cache = LeafCache::new();+ assert_eq!(cache.capacity(), DEFAULT_LEAF_CACHE_CAPACITY);+ assert!(cache.is_empty());+ cache.insert(7, leaf(10));+ assert_eq!(cache.len(), 1);+ let hit = cache.get(7).expect("cached");+ assert_eq!(hit.len(), 1);+ assert_eq!(hit[0].tile_id_lo, 10);+ assert!(cache.get(8).is_none(), "a miss is None");+}++#[test]+fn the_cache_evicts_least_recently_used() {+ let cache = LeafCache::with_capacity(2);+ cache.insert(1, leaf(1));+ cache.insert(2, leaf(2));+ // Touch 1 so 2 is the eviction candidate.+ let _ = cache.get(1);+ cache.insert(3, leaf(3));+ assert!(cache.get(1).is_some(), "recently used survives");+ assert!(cache.get(2).is_none(), "least-recently-used is evicted");+ assert!(cache.get(3).is_some());+ assert_eq!(cache.len(), 2);+}++#[test]+fn a_zero_capacity_still_holds_one_leaf() {+ let cache = LeafCache::with_capacity(0);+ assert_eq!(cache.capacity(), 1);+ cache.insert(1, leaf(1));+ assert!(cache.get(1).is_some());+}++#[test]+fn a_racing_insert_keeps_one_copy() {+ let cache = LeafCache::new();+ let first = cache.insert(9, leaf(1));+ let second = cache.insert(9, leaf(2));+ assert!(Arc::ptr_eq(&first, &second), "the loser uses the winner's copy");+ assert_eq!(cache.len(), 1);+ assert_eq!(cache.get(9).expect("cached")[0].tile_id_lo, 1);+}++#[test]+fn the_cache_shares_across_threads() {+ let cache = Arc::new(LeafCache::new());+ let mut handles = Vec::new();+ for i in 0..8u64 {+ let cache = Arc::clone(&cache);+ handles.push(std::thread::spawn(move || {+ cache.insert(i, leaf(i as u32));+ // Every thread reads every leaf; concurrent gets are safe.+ for j in 0..8u64 {+ let _ = cache.get(j);+ }+ }));+ }+ for h in handles {+ h.join().expect("worker");+ }+ assert_eq!(cache.len(), 8);+ for i in 0..8u64 {+ assert!(cache.get(i).is_some(), "leaf {i} survived the race");+ }+}++/// Two archive views over one cache fetch a shared leaf once.+///+/// The cost contract the container exists to hold — open is one request, a+/// warm tile one, a cold tile two — now holds *across* readers: the second+/// view's tile costs one request (its body) because the first view's leaf+/// fetch already populated the shared cache. Before the shared cache this+/// second view paid two.+#[test]+fn two_archives_over_one_cache_fetch_a_shared_leaf_once() {+ use tilecodec::mamaps::body::{Body, Feature, Layer, Part, DEFAULT_EXTENT, GEOM_LINE, WINDING_OUTER};+ use tilecodec::mamaps::dict;+ use tilecodec::mamaps::read::MamapsArchive;+ use tilecodec::mamaps::write::{Options, StreamWriter};+ use tilecodec::pmtiles::tile_id;+ use tilecodec::proto::Result;+ use tilecodec::stream::RangeReader;++ struct Counting {+ bytes: Vec<u8>,+ requests: std::cell::RefCell<Vec<(u64, u32)>>,+ }+ impl RangeReader for Counting {+ fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+ self.requests.borrow_mut().push((offset, length));+ if offset >= self.bytes.len() as u64 {+ return Ok(Vec::new());+ }+ let end = (offset + length as u64).min(self.bytes.len() as u64);+ Ok(self.bytes[offset as usize..end as usize].to_vec())+ }+ }++ fn body_for(seed: i16) -> Body {+ let mut roads = Layer::new(dict::LAYER_ROADS);+ roads.features.push(Feature {+ kind: 45,+ kind_detail: dict::NONE,+ geom_type: GEOM_LINE,+ flags: 0,+ name_idx: tilecodec::mamaps::body::NAME_NONE,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ roads.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });+ roads.coords = vec![(0, 0), (seed, seed)];+ Body {+ extent: DEFAULT_EXTENT,+ layers: vec![roads],+ names: Vec::new(),+ ids: Vec::new(),+ turn_lanes: Vec::new(),+ buildings: Vec::new(),+ heightmap: None,+ carriageways: Vec::new(),+ convention: None,+ region_links: Vec::new(),+ }+ }++ // Several leaves so a tile really has a leaf to share.+ let mut tiles: Vec<(u8, u64, u64, i16)> = Vec::new();+ for z in 0..=3u8 {+ for x in 0..(1u64 << z) {+ for y in 0..(1u64 << z) {+ tiles.push((z, x, y, (tile_id(z, x, y) + 1) as i16));+ }+ }+ }+ let options = Options { leaf_entry_capacity: 16, ..Options::default() };+ let mut rows: Vec<(u64, i16)> =+ tiles.iter().map(|(z, x, y, seed)| (tile_id(*z, *x, *y), *seed)).collect();+ rows.sort_by_key(|(id, _)| *id);+ let mut writer = StreamWriter::new(options).expect("options");+ for (id, seed) in rows {+ writer.append(id, &body_for(seed)).expect("append");+ }+ let bytes = writer.finish().expect("finish");++ let leaves = Arc::new(LeafCache::new());+ let count = |a: &MamapsArchive<Counting>| a.reader().requests.borrow().len();++ // First view: cold tile costs two (leaf + body).+ let first = MamapsArchive::open_with_cache(+ Counting { bytes: bytes.clone(), requests: std::cell::RefCell::new(Vec::new()) },+ Arc::clone(&leaves),+ )+ .expect("open");+ assert!(first.tile(3, 0, 0).expect("read").is_some());+ assert_eq!(count(&first), 3, "open plus a cold tile: prefix, leaf, body");++ // Second view over the same bytes and the same cache: the same tile costs+ // one request (its body) — the leaf came from the shared cache, and the+ // prefix open is its own one request.+ let second = MamapsArchive::open_with_cache(+ Counting { bytes, requests: std::cell::RefCell::new(Vec::new()) },+ Arc::clone(&leaves),+ )+ .expect("open");+ assert!(second.tile(3, 0, 0).expect("read").is_some());+ assert_eq!(+ count(&second),+ 2,+ "open plus a shared-leaf tile: prefix and body, no second leaf fetch"+ );+}
scripts/maps/tile_build/src/bin/mamaps_probe.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_probe.rs b/scripts/maps/tile_build/src/bin/mamaps_probe.rsindex cf9d2485cd..eb018104dd 100644--- a/scripts/maps/tile_build/src/bin/mamaps_probe.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_probe.rs@@ -81,7 +81,7 @@ fn main() -> ExitCode { if args[2] == "--sidecars" { return sidecars(&args[1]); }- let mut archive = match MamapsArchive::open(FileRanges { file: std::sync::Mutex::new(file) }) {+ let archive = match MamapsArchive::open(FileRanges { file: std::sync::Mutex::new(file) }) { Ok(a) => a, Err(e) => { eprintln!("mamaps_probe: open: {e}");@@ -297,7 +297,7 @@ fn breakdown(path: &str, samples_per_zoom: usize) -> ExitCode { } println!("total stored bodies: {:.3} GB", total_stored as f64 / 1e9); // Sampled bodies per zoom: heightmap share + raw sizes.- let mut archive = match MamapsArchive::open(FileRanges {+ let archive = match MamapsArchive::open(FileRanges { file: std::sync::Mutex::new(File::open(path).expect("open")), }) { Ok(a) => a,@@ -571,7 +571,7 @@ fn layer_breakdown(path: &str, samples_per_zoom: usize) -> ExitCode { let layer_name = |id: u8| -> String { dictionary.layer_name(id).unwrap_or("?").to_string() };- let mut archive = match MamapsArchive::open(FileRanges {+ let archive = match MamapsArchive::open(FileRanges { file: std::sync::Mutex::new(File::open(path).expect("open")), }) { Ok(a) => a,