mln-rs-runtime 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! Styles that load from the cache and the network, and what a loaded style
//! reports and requests.

use std::collections::BTreeSet;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, channel};

use mln_engine::camera::CameraOptions;
use mln_engine::map::{MapEvent, MapMode};
use mln_engine::storage::chrono::Timestamp;
use mln_engine::storage::{Kind, Response};
use mln_runtime::{ResourceRequest, Runtime, RuntimeEventKind, RuntimeOptions};
use parking_lot::Mutex;
use serde_json::Value;

use crate::support::still::{
    StillMap, StillOptions, center_pixel, differing, file_response, ll, not_found, read_file, recv, serve,
};
use crate::support::{EventLog, TempDir, TestRuntime, map, wait};

/// A runtime that keeps its cache in `dir`.
fn cached_runtime(dir: &TempDir) -> TestRuntime {
    let options = RuntimeOptions { cache_path: Some(dir.path("cache.db")), ..RuntimeOptions::default() };
    TestRuntime(Runtime::new(&options).expect("a runtime"))
}

/// `response`, which went stale at the epoch.
fn expired(mut response: Response) -> Response {
    response.caching.expires = Some(Timestamp::from_secs(0));
    response
}

/// The last segment of `url`'s path.
fn file_name(url: &str) -> &str {
    url.rsplit('/').next().unwrap_or(url)
}

/// A provider that holds its requests until it opens, and then answers them
/// and those after with `answer`.
struct Gate<F> {
    /// Whether it opened, and the requests it holds until then.
    state: Mutex<(bool, Vec<ResourceRequest>)>,
    answer: F,
}

impl<F: Fn(&ResourceRequest) -> Response + Send + Sync + 'static> Gate<F> {
    /// Sets `runtime`'s provider to one that holds every request, and
    /// answers them with `answer` once [`open`](Self::open) is called.
    fn install(runtime: &Runtime, answer: F) -> Arc<Self> {
        let gate = Arc::new(Gate { state: Mutex::new((false, Vec::new())), answer });
        let provider = Arc::clone(&gate);
        wait(runtime.set_resource_provider(move |request: ResourceRequest| {
            let mut state = provider.state.lock();
            if state.0 {
                drop(state);
                let response = (provider.answer)(&request);
                let _ = request.respond(response);
            } else {
                state.1.push(request);
            }
        }));
        gate
    }

    /// Answers the requests held so far, and those after at once.
    fn open(&self) {
        let held = {
            let mut state = self.state.lock();
            state.0 = true;
            std::mem::take(&mut state.1)
        };
        for request in held {
            let response = (self.answer)(&request);
            let _ = request.respond(response);
        }
    }
}

/// A style with no sources publishes an update once it loads: a continuous
/// map whose camera was set first, so that the style's default camera
/// doesn't jump it, still renders the style and finishes loading.
#[test]
fn a_sourceless_style_loaded_after_the_camera_renders() {
    let map = StillMap::continuous();
    map.jump(CameraOptions { center: Some(ll(10.0, 20.0)), zoom: Some(3.0), ..Default::default() });
    map.load_json(
        r##"{"version": 8, "sources": {}, "layers": [
            {"id": "bg", "type": "background", "paint": {"background-color": "#00ff00"}}
        ]}"##,
    );

    map.settle();
    map.events.wait_for(|event| matches!(event.kind, RuntimeEventKind::Map(MapEvent::LoadingFinished)));
    assert_eq!(center_pixel(&map.image()), [0, 255, 0, 255]);
}

/// A map shows what the cache holds while the network doesn't answer, even
/// once it has expired: what the map that filled the cache showed.
#[test]
fn an_expired_cache_stands_in_for_a_network_that_never_answers() {
    let style_url = "http://127.0.0.1:3000/style.json";
    let dir = TempDir::new();
    let online = {
        // The cache gets expired copies of everything the map needs.
        let seeding = StillMap::on(cached_runtime(&dir), StillOptions::default());
        serve(&seeding.runtime, |resource| {
            let file = match file_name(&resource.url) {
                "sprite.json" | "sprite.png" | "streets.json" | "style.json" | "0-0-0.vector.pbf" => {
                    file_name(&resource.url).to_owned()
                }
                "0-255.pbf" => "glyph.pbf".to_owned(),
                _ => return not_found(),
            };
            expired(file_response(&format!("test/fixtures/map/offline/{file}")))
        });
        seeding.load_url(style_url);
        seeding.render()
    };

    // The network never answers: the gate never opens.
    let map = StillMap::on(cached_runtime(&dir), StillOptions::default());
    Gate::install(&map.runtime, |_: &ResourceRequest| not_found());
    map.load_url(style_url);
    let offline = map.render();
    assert!(offline.data.chunks(4).any(|pixel| pixel[3] > 0), "the map draws");
    assert_eq!(0, differing(&offline, &online));
}

const STYLE_URL: &str = "https://example.com/maps/test";

/// A runtime whose cache holds a copy of empty.json for [`STYLE_URL`] that
/// has expired, and the revalidations of that copy that its provider gets
/// after, unanswered.
fn expired_style_runtime(dir: &TempDir) -> (TestRuntime, Receiver<ResourceRequest>) {
    let runtime = cached_runtime(dir);
    let (sender, revalidations): (Sender<ResourceRequest>, _) = channel();
    let sender = Mutex::new(sender);
    wait(runtime.set_resource_provider(move |request: ResourceRequest| {
        // The cached copy is usable, so the revalidation carries its
        // validators rather than its data.
        if request.resource().prior_caching.expires.is_some() {
            sender.lock().send(request).unwrap();
        } else {
            let _ = request.respond(expired(file_response("test/fixtures/api/empty.json")));
        }
    }));
    // A map caches the expired copy. Released, it cancels its own
    // revalidations, which go: the tests answer their maps' alone.
    let caching = map(&runtime);
    wait(caching.set_style_url(STYLE_URL));
    wait(caching.release());
    while revalidations.try_recv().is_ok() {}
    (runtime, revalidations)
}

/// The next revalidation that a map that's still live waits for.
#[track_caller]
fn live_revalidation(revalidations: &Receiver<ResourceRequest>) -> ResourceRequest {
    loop {
        let revalidation = recv(revalidations);
        if !revalidation.is_cancelled() {
            return revalidation;
        }
    }
}

/// A fresh style with one layer, "revalidated".
fn revalidated_style() -> Response {
    let style = r#"{"version": 8, "sources": {}, "layers": [{"id": "revalidated", "type": "background"}]}"#;
    Response { data: Some(Arc::new(style.as_bytes().to_vec())), ..Response::default() }
}

/// A map that shows an expired style from the cache takes the style that
/// its revalidation brings, which loads on the runtime's thread and reports
/// that it loaded, unless an edit to the style, or a projection set at
/// runtime, came before it.
#[test]
fn a_revalidated_style_replaces_an_expired_one_that_nothing_edited() {
    for edit in ["nothing", "a layer", "the projection"] {
        let dir = TempDir::new();
        let (runtime, revalidations) = expired_style_runtime(&dir);
        let map = map(&runtime);
        wait(map.set_style_url(STYLE_URL));
        let revalidation = live_revalidation(&revalidations);
        let log = EventLog::install(&runtime);
        match edit {
            "a layer" => {
                wait(map.add_style_layer_json(r#"{"id": "bg", "type": "background"}"#, None));
            }
            "the projection" => {
                wait(map.set_style_root_property("projection", r#"{"type": "globe"}"#));
            }
            _ => {}
        }
        revalidation.respond(revalidated_style()).unwrap();
        if edit == "nothing" {
            log.wait_for(|event| matches!(event.kind, RuntimeEventKind::Map(MapEvent::StyleLoaded)));
            assert!(wait(map.style_layer("revalidated")).is_some(), "the revalidated style loads");
            continue;
        }
        // The edit stays, and the revalidated style never loads.
        if edit == "a layer" {
            assert!(wait(map.style_layer("bg")).is_some(), "the added layer stays");
        } else {
            let projection = wait(map.style_root_property("projection")).expect("a projection");
            let projection: Value = serde_json::from_str(&projection).unwrap();
            assert_eq!(projection["type"], "globe", "{projection}");
        }
        assert!(wait(map.style_layer("revalidated")).is_none(), "{edit}");
    }
}

/// The fixture of the expired sprite test for the file `file`: its style,
/// source and sprite sheet's JSON, or the offline test's tile and sprite
/// image.
fn online_fixture(file: &str) -> Response {
    match file {
        "sprite.png" | "0-0-0.vector.pbf" => file_response(&format!("test/fixtures/map/offline/{file}")),
        _ => file_response(&format!("test/fixtures/map/online/{file}")),
    }
}

/// The network's copy of the expired test's sprite sheet index: the cached
/// copy's images "a", "b" and "c", and a new one, "d".
fn revalidated_sprite_json() -> Response {
    let mut index: Value = serde_json::from_str(&read_file("test/fixtures/map/online/sprite.json")).unwrap();
    index["d"] = index["a"].clone();
    Response { data: Some(Arc::new(index.to_string().into_bytes())), ..Response::default() }
}

/// A sprite sheet that expired in the cache loads again once the network
/// answers, after the map has loaded from the cache, and its images stay in
/// the style.
#[test]
fn an_expired_sprite_sheet_loads_again_once_the_network_answers() {
    let style_url = "http://127.0.0.1:3000/online/style.json";
    let dir = TempDir::new();
    {
        // The cache gets copies of the style, its source and tile that never
        // expire, and expired ones of the sprite sheet.
        let seeding = StillMap::on(cached_runtime(&dir), StillOptions::default());
        serve(&seeding.runtime, |resource| {
            let response = online_fixture(file_name(&resource.url));
            if matches!(resource.kind, Kind::SpriteJSON | Kind::SpriteImage) { expired(response) } else { response }
        });
        seeding.load_url(style_url);
        seeding.render();
    }

    let map = StillMap::on(cached_runtime(&dir), StillOptions { mode: MapMode::Continuous, ..StillOptions::default() });
    let sprites_served = Arc::new(Mutex::new(BTreeSet::new()));
    let gate = Gate::install(&map.runtime, {
        let sprites_served = Arc::clone(&sprites_served);
        move |request: &ResourceRequest| {
            let resource = request.resource();
            let file = file_name(&resource.url).to_owned();
            match resource.kind {
                Kind::SpriteJSON | Kind::SpriteImage => {
                    sprites_served.lock().insert(file.clone());
                    if resource.kind == Kind::SpriteJSON { revalidated_sprite_json() } else { online_fixture(&file) }
                }
                // The cache asks the network about every copy. These are
                // current: a new style would replace the one loaded, and its
                // images, until its own sprite sheet loads.
                _ => Response { not_modified: true, ..Response::default() },
            }
        }
    });
    map.load_url(style_url);
    map.settle();
    assert!(sprites_served.lock().is_empty());
    assert!(wait(map.map.style_image("a")).is_some(), "the cached sprite sheet loads");
    assert!(wait(map.map.style_image("d")).is_none());

    // The network answers once the map has loaded from the cache, as it
    // would coming online then. Each sprite sheet that loads ends with a
    // `SpriteLoaded`, and the network's has "d".
    let mut from = map.events.events().len();
    gate.open();
    while wait(map.map.style_image("d")).is_none() {
        map.events.wait_until(|events| {
            let loaded = events[from..]
                .iter()
                .position(|event| matches!(event.kind, RuntimeEventKind::Map(MapEvent::SpriteLoaded(_))));
            loaded.inspect(|index| from += index + 1).is_some()
        });
    }
    assert_eq!(BTreeSet::from(["sprite.json".to_owned(), "sprite.png".to_owned()]), *sprites_served.lock());
    for image in ["a", "b", "c"] {
        assert!(wait(map.map.style_image(image)).is_some(), "{image}");
    }
}

/// Switching styles drops the glyphs of the font stacks the new style no
/// longer uses, so switching back requests them again, and keeps the glyphs
/// of those it still uses. The glyphs stay out of the ambient cache, so each
/// load of them asks the provider before the still is drawn.
#[test]
fn style_switch_evicts_the_glyphs_of_unused_font_stacks() {
    let map = StillMap::still();
    let requests = serve(&map.runtime, |resource| match resource.kind {
        Kind::Glyphs => Response { no_store: true, ..file_response("test/fixtures/resources/glyphs.pbf") },
        _ => not_found(),
    });
    let style = |fonts: &[&str]| {
        let layers: Vec<String> = fonts
            .iter()
            .map(|font| {
                format!(
                    r#"{{"id": "{font}", "type": "symbol", "source": "point",
                        "layout": {{"text-field": "a", "text-font": ["{font}"]}}}}"#
                )
            })
            .collect();
        format!(
            r#"{{
                "version": 8,
                "glyphs": "test://glyphs/{{fontstack}}/{{range}}.pbf",
                "sources": {{
                    "point": {{"type": "geojson", "data": {{"type": "Point", "coordinates": [0, 0]}}}}
                }},
                "layers": [{}]
            }}"#,
            layers.join(", ")
        )
    };

    map.load_json(&style(&["Kept", "Dropped"]));
    map.render();
    assert_eq!(requests.count(Kind::Glyphs), 2, "{:?}", requests.all());
    requests.clear();
    map.load_json(&style(&["Kept"]));
    map.render();
    assert_eq!(requests.count(Kind::Glyphs), 0, "{:?}", requests.all());

    map.load_json(&style(&["Kept", "Dropped"]));
    map.render();
    assert_eq!(requests.urls(Kind::Glyphs), ["test://glyphs/Dropped/0-255.pbf"]);
}