mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
// The file sources' tests, and the helpers they and the offline tests share.

#![cfg_attr(not(feature = "sqlite"), expect(dead_code, reason = "some helpers serve only the SQLite tests"))]

mod asset_file_source;
#[cfg(feature = "sqlite")]
mod database_file_source;
mod http_file_source;
#[cfg(feature = "sqlite")]
mod loader;
mod local_file_source;
#[cfg(feature = "sqlite")]
mod mbtiles_file_source;
mod network;
#[cfg(feature = "sqlite")]
mod offline_database;
mod online_file_source;
mod pmtiles_file_source;

use std::path::PathBuf;
use std::sync::{Arc, Once, mpsc};

use parking_lot::Mutex;
use tracing::{Event, Level, Subscriber};
use tracing_subscriber::Layer;
use tracing_subscriber::layer::{Context, SubscriberExt as _};

use crate::storage::file_source::{FileSource, FileSourceExt};
use crate::storage::resource::Resource;
use crate::storage::response::{Data, Response};

/// The path of a fixture in the package's testdata/test/fixtures.
pub(crate) fn fixture(relative: &str) -> PathBuf {
    let package = std::env::var_os("CARGO_MANIFEST_DIR").expect("Cargo sets CARGO_MANIFEST_DIR");
    PathBuf::from(package).join("testdata/test/fixtures").join(relative)
}

/// Requests `resource` from `source` and waits for its first answer, which
/// the source sends from any thread.
pub(crate) fn answer(source: &(impl FileSource + ?Sized), resource: &Resource) -> Response {
    let (answered, answer) = mpsc::channel();
    let _request = source.request(resource, move |response| {
        let _ = answered.send(response);
    });
    answer.recv().expect("an answer")
}

/// A pool for a test's file sources.
pub(crate) fn pool() -> crate::exec::pool::Pool {
    crate::exec::pool::Pool::new(4)
}

/// `size` bytes that don't compress.
pub(crate) fn incompressible(size: usize) -> Data {
    // xorshift64*: any seed but zero gives a sequence without a pattern
    // deflate can use.
    let mut state = 0x9E37_79B9_7F4A_7C15_u64;
    let bytes = (0..size)
        .map(|_| {
            state ^= state >> 12;
            state ^= state << 25;
            state ^= state >> 27;
            (state.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 56) as u8
        })
        .collect();
    Arc::new(bytes)
}

/// Holds a worker's thread in the task that `send` sends it, after the
/// work already sent to it, until the returned guard drops. It returns once
/// the thread is held, so the work sent meanwhile queues up and runs in one
/// go after the drop. Drop the guard before the worker's owner, whose drop
/// waits for the worker.
pub(crate) fn pause(send: impl FnOnce(Box<dyn FnOnce() + Send>)) -> Paused {
    let (paused, is_paused) = mpsc::channel();
    let (resume, resumed) = mpsc::channel::<()>();
    send(Box::new(move || {
        let _ = paused.send(());
        // Returns once `Paused` drops its sender.
        let _ = resumed.recv();
    }));
    is_paused.recv().expect("the thread holds");
    Paused { _resume: resume }
}

/// Resumes the thread that [`pause`] holds when it drops.
pub(crate) struct Paused {
    _resume: mpsc::Sender<()>,
}

/// A fresh path in a temporary directory of its own. The directory is
/// unique to this process, so concurrent test runs never share a file, and
/// dropping the guard removes it with everything SQLite wrote beside the
/// path.
pub(crate) fn temp_path(name: &str) -> TempPath {
    static COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    let dir = std::env::temp_dir().join(format!("mln-storage-test-{}-{n}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("Cannot create {}: {e}", dir.display()));
    let path = dir.join(name).to_string_lossy().into_owned();
    TempPath { dir, path }
}

/// A path from [`temp_path`], usable as a `&str`.
pub(crate) struct TempPath {
    dir: PathBuf,
    path: String,
}

impl TempPath {
    /// Another path in the same directory.
    pub(crate) fn sibling(&self, name: &str) -> String {
        self.dir.join(name).to_string_lossy().into_owned()
    }
}

impl std::ops::Deref for TempPath {
    type Target = str;

    fn deref(&self) -> &str {
        &self.path
    }
}

impl std::fmt::Display for TempPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.path)
    }
}

impl AsRef<std::path::Path> for TempPath {
    fn as_ref(&self) -> &std::path::Path {
        self.path.as_ref()
    }
}

impl Drop for TempPath {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

/// A function that sees the rendered fields of every thread's warnings and
/// errors.
type Watch = Box<dyn Fn(&str) + Send>;

static WATCH: Mutex<Option<Watch>> = Mutex::new(None);

/// Hands the library's warnings and errors to the process's [`watch`].
struct Watcher;

impl<S: Subscriber> Layer<S> for Watcher {
    fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) {
        let meta = event.metadata();
        if !meta.target().starts_with("mln_") || *meta.level() > Level::WARN {
            return;
        }
        let mut message = String::new();
        event.record(&mut |field: &tracing::field::Field, value: &dyn std::fmt::Debug| {
            use std::fmt::Write as _;
            let _ = write!(message, " {}={value:?}", field.name());
        });
        if let Some(watch) = WATCH.lock().as_ref() {
            watch(&message);
        }
    }
}

/// Hands the rendered fields of every thread's warnings and errors to
/// `watch` until the guard drops, for a test of work on a thread it doesn't
/// own.
pub(crate) fn watch(watch: impl Fn(&str) + Send + 'static) -> impl Drop {
    struct Unwatch;
    impl Drop for Unwatch {
        fn drop(&mut self) {
            WATCH.lock().take();
        }
    }
    static INSTALL: Once = Once::new();
    INSTALL.call_once(|| {
        tracing::subscriber::set_global_default(tracing_subscriber::registry().with(Watcher))
            .expect("the test binary has no other global subscriber");
    });
    *WATCH.lock() = Some(Box::new(watch));
    Unwatch
}