#![allow(clippy::unwrap_used)]
use std::collections::HashMap;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;
use arrow::array::{
Array, ArrayRef, BinaryArray, Float32Array, Float64Builder, ListArray, ListBuilder,
StringArray, StringBuilder, StructArray,
};
use arrow::buffer::OffsetBuffer;
use arrow::datatypes::{DataType, Field, Fields, Schema};
use arrow::record_batch::RecordBatch;
use clap::Parser;
use geolith_cli::tile::mvt::proto;
use parquet::arrow::ArrowWriter;
use prost::Message;
struct Segment {
id: &'static str,
subtype: &'static str,
class: &'static str,
line: [(f64, f64); 2],
flags: Vec<(&'static str, Option<(f64, f64)>)>,
}
fn wkb_line(line: &[(f64, f64)]) -> Vec<u8> {
let mut b = vec![1u8];
b.extend_from_slice(&2u32.to_le_bytes());
b.extend_from_slice(&(line.len() as u32).to_le_bytes());
for (x, y) in line {
b.extend_from_slice(&x.to_le_bytes());
b.extend_from_slice(&y.to_le_bytes());
}
b
}
fn road_flags(rows: &[Segment]) -> ListArray {
let mut values = ListBuilder::new(StringBuilder::new());
let mut between = ListBuilder::new(Float64Builder::new());
let mut lengths = Vec::with_capacity(rows.len());
for row in rows {
lengths.push(row.flags.len());
for (flag, range) in &row.flags {
values.values().append_value(flag);
values.append(true);
match range {
Some((a, b)) => {
between.values().append_value(*a);
between.values().append_value(*b);
between.append(true);
}
None => between.append(false),
}
}
}
let values = values.finish();
let between = between.finish();
let fields = Fields::from(vec![
Field::new("values", values.data_type().clone(), true),
Field::new("between", between.data_type().clone(), true),
]);
let rules = StructArray::new(
fields.clone(),
vec![Arc::new(values) as ArrayRef, Arc::new(between)],
None,
);
ListArray::new(
Arc::new(Field::new("item", DataType::Struct(fields), true)),
OffsetBuffer::from_lengths(lengths),
Arc::new(rules),
None,
)
}
fn write_segments(dir: &Path, rows: &[Segment]) {
write_segment_file(dir, "part-00000.parquet", rows);
}
fn write_segment_file(dir: &Path, file: &str, rows: &[Segment]) {
let part = dir.join("theme=transportation/type=segment");
std::fs::create_dir_all(&part).expect("partition dir");
let bbox_fields = Fields::from(vec![
Field::new("xmin", DataType::Float32, false),
Field::new("ymin", DataType::Float32, false),
Field::new("xmax", DataType::Float32, false),
Field::new("ymax", DataType::Float32, false),
]);
let coord = |f: fn(f64, f64) -> f64, i: usize| -> Float32Array {
rows.iter()
.map(|r| {
let [(x0, y0), (x1, y1)] = r.line;
let pair = if i == 0 { (x0, x1) } else { (y0, y1) };
f(pair.0, pair.1) as f32
})
.collect()
};
let bbox = StructArray::new(
bbox_fields.clone(),
vec![
Arc::new(coord(f64::min, 0)) as ArrayRef,
Arc::new(coord(f64::min, 1)),
Arc::new(coord(f64::max, 0)),
Arc::new(coord(f64::max, 1)),
],
None,
);
let flags = road_flags(rows);
let wkb: Vec<Vec<u8>> = rows.iter().map(|r| wkb_line(&r.line)).collect();
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Utf8, false),
Field::new("geometry", DataType::Binary, false),
Field::new("bbox", DataType::Struct(bbox_fields), false),
Field::new("subtype", DataType::Utf8, true),
Field::new("class", DataType::Utf8, true),
Field::new("road_flags", flags.data_type().clone(), true),
]));
let batch = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.id))) as ArrayRef,
Arc::new(BinaryArray::from_iter_values(wkb.iter())),
Arc::new(bbox),
Arc::new(StringArray::from_iter_values(
rows.iter().map(|r| r.subtype),
)),
Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.class))),
Arc::new(flags),
],
)
.expect("record batch");
let file = std::fs::File::create(part.join(file)).expect("parquet file");
let mut writer = ArrowWriter::try_new(file, schema, None).expect("writer");
writer.write(&batch).expect("write");
writer.close().expect("close");
}
fn write_square_shapefile(dir: &Path, name: &str, min: f64, max: f64) {
use shapefile::dbase::{Record, TableWriterBuilder};
use shapefile::record::polygon::{Polygon, PolygonRing};
use shapefile::{Point, Writer};
std::fs::create_dir_all(dir).expect("shapefile dir");
let mut writer = Writer::from_path(dir.join(format!("{name}.shp")), TableWriterBuilder::new())
.expect("shapefile writer");
let ring = vec![
Point::new(min, min),
Point::new(min, max),
Point::new(max, max),
Point::new(max, min),
Point::new(min, min),
];
writer
.write_shape_and_record(
&Polygon::with_rings(vec![PolygonRing::Outer(ring)]),
&Record::default(),
)
.expect("write polygon");
}
fn read_varint(buf: &[u8], pos: &mut usize) -> u64 {
let mut value = 0u64;
let mut shift = 0;
loop {
let byte = buf[*pos];
*pos += 1;
value |= u64::from(byte & 0x7f) << shift;
if byte & 0x80 == 0 {
return value;
}
shift += 7;
}
}
fn decompress(bytes: &[u8], compression: u8) -> Vec<u8> {
match compression {
1 => bytes.to_vec(),
2 => {
let mut out = Vec::new();
flate2::read::GzDecoder::new(bytes)
.read_to_end(&mut out)
.expect("gzip");
out
}
other => panic!("unexpected PMTiles compression {other}"),
}
}
fn u64_at(buf: &[u8], at: usize) -> u64 {
u64::from_le_bytes(buf[at..at + 8].try_into().expect("8 bytes"))
}
fn read_all_tiles(archive: &[u8]) -> HashMap<u64, Vec<u8>> {
assert_eq!(&archive[..7], b"PMTiles");
assert_eq!(archive[7], 3);
let (root_off, root_len) = (u64_at(archive, 8), u64_at(archive, 16));
let leaf_off = u64_at(archive, 40);
let data_off = u64_at(archive, 56);
let (internal, tile_comp) = (archive[97], archive[98]);
let mut tiles = HashMap::new();
let mut stack = vec![(root_off, root_len)];
while let Some((off, len)) = stack.pop() {
let dir = decompress(&archive[off as usize..(off + len) as usize], internal);
let mut p = 0;
let n = read_varint(&dir, &mut p) as usize;
let mut ids = Vec::with_capacity(n);
let mut last = 0;
for _ in 0..n {
last += read_varint(&dir, &mut p);
ids.push(last);
}
let runs: Vec<u64> = (0..n).map(|_| read_varint(&dir, &mut p)).collect();
let lens: Vec<u64> = (0..n).map(|_| read_varint(&dir, &mut p)).collect();
let mut offs = Vec::with_capacity(n);
for i in 0..n {
let raw = read_varint(&dir, &mut p);
offs.push(if raw == 0 && i > 0 {
offs[i - 1] + lens[i - 1]
} else {
raw - 1
});
}
for i in 0..n {
if runs[i] == 0 {
stack.push((leaf_off + offs[i], lens[i]));
continue;
}
let start = (data_off + offs[i]) as usize;
let payload = decompress(&archive[start..start + lens[i] as usize], tile_comp);
for k in 0..runs[i] {
tiles.insert(ids[i] + k, payload.clone());
}
}
}
tiles
}
fn zoom_of(tile_id: u64) -> u8 {
let (mut z, mut base) = (0u8, 0u64);
while tile_id >= base + 4u64.pow(u32::from(z)) {
base += 4u64.pow(u32::from(z));
z += 1;
}
z
}
#[derive(Debug)]
struct Road {
zoom: u8,
kind: String,
detail: Option<String>,
bridge: bool,
reference: Option<String>,
network: Option<String>,
shield: Option<String>,
}
fn roads_in(tiles: &HashMap<u64, Vec<u8>>) -> Vec<Road> {
let mut out = Vec::new();
for (&id, bytes) in tiles {
let tile = proto::Tile::decode(bytes.as_slice()).expect("valid MVT");
for layer in tile.layers.iter().filter(|l| l.name == "roads") {
for f in &layer.features {
let mut props: HashMap<&str, &proto::tile::Value> = HashMap::new();
for pair in f.tags.chunks(2) {
props.insert(
layer.keys[pair[0] as usize].as_str(),
&layer.values[pair[1] as usize],
);
}
let text = |k: &str| props.get(k).and_then(|v| v.string_value.clone());
out.push(Road {
zoom: zoom_of(id),
kind: text("kind").unwrap_or_default(),
detail: text("kind_detail"),
bridge: props.get("is_bridge").and_then(|v| v.bool_value) == Some(true),
reference: text("ref"),
network: text("network"),
shield: text("shield_text"),
});
}
}
}
out
}
fn build(rows: &[Segment]) -> Vec<Road> {
build_with(rows, "overture", "-0.3,51.4,0.3,51.6", None)
}
fn build_with(rows: &[Segment], source: &str, bbox: &str, osm_pbf: Option<&Path>) -> Vec<Road> {
let india =
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/pune-soi-boundary.geojson");
let mut extra = vec![
"--roads-source".to_string(),
source.into(),
"--india-boundary".into(),
india.to_string_lossy().into_owned(),
];
if let Some(pbf) = osm_pbf {
extra.extend(["--osm-pbf".into(), pbf.to_string_lossy().into_owned()]);
}
roads_in(&read_all_tiles(&run_fixture(rows, bbox, 12, &extra)))
}
fn run_fixture(rows: &[Segment], bbox: &str, max_zoom: u8, extra: &[String]) -> Vec<u8> {
run_fixture_on(rows, bbox, max_zoom, extra, None)
}
fn run_fixture_on(
rows: &[Segment],
bbox: &str,
max_zoom: u8,
extra: &[String],
threads: Option<usize>,
) -> Vec<u8> {
run_fixture_with(rows, bbox, max_zoom, extra, threads, &|_| {})
}
fn run_fixture_with(
rows: &[Segment],
bbox: &str,
max_zoom: u8,
extra: &[String],
threads: Option<usize>,
more_sources: &dyn Fn(&Path),
) -> Vec<u8> {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
write_segments(&root.join("overture"), rows);
more_sources(&root.join("overture"));
rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
let out = root.join("out.pmtiles");
let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
let mut args = vec![
"geolith".to_string(),
"--data".into(),
arg("overture"),
"--natural-earth".into(),
arg("ne.sqlite"),
"--land-polygons".into(),
arg("land"),
"--water-polygons".into(),
arg("water"),
"--output".into(),
out.to_string_lossy().into_owned(),
"--tmpdir".into(),
arg("tmp"),
"--node-store".into(),
arg("nodes.bin"),
"--no-conflate".into(),
"--bbox".into(),
bbox.into(),
"--max-zoom".into(),
max_zoom.to_string(),
];
args.extend_from_slice(extra);
let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");
match threads {
Some(n) => rayon::ThreadPoolBuilder::new()
.num_threads(n)
.build()
.expect("thread pool")
.install(|| geolith_cli::run_with_config(&config)),
None => geolith_cli::run_with_config(&config),
}
.expect("pipeline runs");
std::fs::read(&out).expect("archive")
}
fn write_named_segment(dir: &Path, primary: &str, common: &[(&str, &str)]) {
use arrow::array::MapBuilder;
let part = dir.join("theme=transportation/type=segment");
std::fs::create_dir_all(&part).expect("partition dir");
let line = [(-0.05, 51.5), (-0.04, 51.5)];
let bbox_fields = Fields::from(vec![
Field::new("xmin", DataType::Float32, false),
Field::new("ymin", DataType::Float32, false),
Field::new("xmax", DataType::Float32, false),
Field::new("ymax", DataType::Float32, false),
]);
let one = |v: f32| Arc::new(Float32Array::from(vec![v])) as ArrayRef;
let bbox = StructArray::new(
bbox_fields.clone(),
vec![one(-0.05), one(51.5), one(-0.04), one(51.5)],
None,
);
let mut map = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new());
for (lang, name) in common {
map.keys().append_value(lang);
map.values().append_value(name);
}
map.append(true).expect("map row");
let common_array = map.finish();
let primary_array = StringArray::from(vec![primary]);
let names_fields = Fields::from(vec![
Field::new("primary", DataType::Utf8, true),
Field::new("common", common_array.data_type().clone(), true),
]);
let names = StructArray::new(
names_fields.clone(),
vec![Arc::new(primary_array) as ArrayRef, Arc::new(common_array)],
None,
);
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Utf8, false),
Field::new("geometry", DataType::Binary, false),
Field::new("bbox", DataType::Struct(bbox_fields), false),
Field::new("subtype", DataType::Utf8, true),
Field::new("class", DataType::Utf8, true),
Field::new("names", DataType::Struct(names_fields), true),
]));
let wkb = wkb_line(&line);
let batch = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(StringArray::from(vec!["named"])) as ArrayRef,
Arc::new(BinaryArray::from_iter_values([wkb.as_slice()])),
Arc::new(bbox),
Arc::new(StringArray::from(vec!["road"])),
Arc::new(StringArray::from(vec!["motorway"])),
Arc::new(names),
],
)
.expect("record batch");
let file = std::fs::File::create(part.join("part-named.parquet")).expect("parquet file");
let mut writer = ArrowWriter::try_new(file, schema, None).expect("writer");
writer.write(&batch).expect("write");
writer.close().expect("close");
}
fn road_attributes(tiles: &HashMap<u64, Vec<u8>>) -> Vec<HashMap<String, String>> {
let mut out = Vec::new();
for bytes in tiles.values() {
let tile = proto::Tile::decode(bytes.as_slice()).expect("valid MVT");
for layer in tile.layers.iter().filter(|l| l.name == "roads") {
for f in &layer.features {
out.push(
f.tags
.chunks(2)
.filter_map(|pair| {
let value = layer.values[pair[1] as usize].string_value.clone()?;
Some((layer.keys[pair[0] as usize].clone(), value))
})
.collect(),
);
}
}
}
out
}
#[test]
fn an_overture_road_carries_its_script_and_language_names() {
let named = |dir: &Path| {
write_named_segment(
dir,
"شارع الملك",
&[
("en", "King Street"),
("ar", "شارع الملك"),
("pnb", "outside the protomaps list"),
],
);
};
let archive = run_fixture_with(
&[],
"-0.06,51.49,-0.02,51.51",
12,
&["--roads-source".to_string(), "overture".into()],
None,
&named,
);
let roads = road_attributes(&read_all_tiles(&archive));
let road = roads
.iter()
.find(|r| r.get("kind").map(String::as_str) == Some("highway"))
.expect("the named motorway is in the archive");
let attr = |k: &str| road.get(k).map(String::as_str);
assert_eq!(attr("name"), Some("شارع الملك"));
assert_eq!(attr("script"), Some("Arabic"));
assert_eq!(attr("name:en"), Some("King Street"));
assert_eq!(attr("name:ar"), Some("شارع الملك"));
assert_eq!(attr("name:pnb"), None);
}
fn layer_counts_at(tiles: &HashMap<u64, Vec<u8>>, zoom: u8) -> HashMap<String, usize> {
let at_zoom: Vec<&Vec<u8>> = tiles
.iter()
.filter(|(id, _)| zoom_of(**id) == zoom)
.map(|(_, bytes)| bytes)
.collect();
assert_eq!(at_zoom.len(), 1, "expected one tile at z{zoom}");
let tile = proto::Tile::decode(at_zoom[0].as_slice()).expect("valid MVT");
tile.layers
.iter()
.map(|l| (l.name.clone(), l.features.len()))
.collect()
}
#[test]
fn a_build_larger_than_one_encode_batch_writes_every_tile() {
for format in ["mvt", "mlt"] {
let args = ["--tile-format".to_string(), format.into()];
let tiles = read_all_tiles(&run_fixture(&[], "-0.3,-0.3,0.3,0.3", 14, &args));
let z14 = tiles.keys().filter(|id| zoom_of(**id) == 14).count();
assert_eq!(z14, 28 * 28, "{format}");
}
}
#[test]
fn a_bbox_build_records_the_bbox_in_the_header() {
let archive = run_fixture(&touching_motorways(), "-0.06,51.49,-0.02,51.51", 12, &[]);
let e7 = |at: usize| i32::from_le_bytes(archive[at..at + 4].try_into().expect("four bytes"));
assert_eq!(
[e7(102), e7(106), e7(110), e7(114)],
[-600_000, 514_900_000, -200_000, 515_100_000]
);
}
fn touching_motorways() -> Vec<Segment> {
[
("west", [(-0.05, 51.5), (-0.04, 51.5)]),
("east", [(-0.04, 51.5), (-0.03, 51.5)]),
]
.into_iter()
.map(|(id, line)| Segment {
id,
subtype: "road",
class: "motorway",
line,
flags: Vec::new(),
})
.collect()
}
#[test]
fn same_attribute_roads_merge_into_one_tile_feature() {
let bbox = "-0.06,51.49,-0.02,51.51";
let tiles = read_all_tiles(&run_fixture(&touching_motorways(), bbox, 12, &[]));
assert_eq!(layer_counts_at(&tiles, 12).get("roads"), Some(&1));
}
#[test]
fn a_bus_route_gives_an_osm_road_no_ref_or_shield() {
let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relations.osm.pbf");
let roads = build_with(&[], "osm", "73.8,18.5,73.9,18.6", Some(&pbf));
let primary: Vec<&Road> = roads
.iter()
.filter(|r| r.detail.as_deref() == Some("primary"))
.collect();
assert!(!primary.is_empty(), "no primary road: {roads:?}");
assert!(
primary
.iter()
.all(|r| r.reference.is_none() && r.network.is_none() && r.shield.is_none()),
"{primary:?}"
);
}
#[test]
fn the_avus_shield_is_its_autobahn_number_on_any_thread_count() {
let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/berlin-a115.osm.pbf");
let extra = [
"--roads-source".to_string(),
"osm".into(),
"--osm-pbf".into(),
pbf.to_string_lossy().into_owned(),
];
let bbox = "13.19,52.40,13.20,52.42";
let serial = run_fixture_on(&[], bbox, 12, &extra, Some(1));
let roads = roads_in(&read_all_tiles(&serial));
assert!(!roads.is_empty(), "no roads");
assert!(
roads.iter().all(|r| r.reference.as_deref() == Some("A 115")
&& r.network.as_deref() == Some("BAB")
&& r.shield.as_deref() == Some("A115")),
"{roads:?}"
);
for threads in [2, 4, 8] {
let parallel = run_fixture_on(&[], bbox, 12, &extra, Some(threads));
assert!(
parallel == serial,
"{threads} threads: archive bytes differ"
);
}
}
#[test]
fn osm_route_attributes_and_merged_roads_are_identical_on_any_thread_count() {
let pbf = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/route-relations-many-blobs.osm.pbf");
let extra = [
"--roads-source".to_string(),
"osm".into(),
"--osm-pbf".into(),
pbf.to_string_lossy().into_owned(),
];
let bbox = "-0.06,51.49,-0.02,51.51";
let serial = run_fixture_on(&[], bbox, 12, &extra, Some(1));
let tiles = read_all_tiles(&serial);
let roads = roads_in(&tiles);
assert!(
!roads.is_empty()
&& roads
.iter()
.all(|r| r.shield.as_deref() == Some("A1") && r.network.as_deref() == Some("BAB")),
"{roads:?}"
);
assert_eq!(
layer_counts_at(&tiles, 12).get("roads"),
Some(&1),
"the two ways merge"
);
for (run, threads) in [8, 4, 8, 2, 8].into_iter().enumerate() {
let parallel = run_fixture_on(&[], bbox, 12, &extra, Some(threads));
assert!(
parallel == serial,
"run {run} on {threads} threads: archive bytes differ: {:?}",
roads_in(&read_all_tiles(¶llel))
);
}
}
#[test]
fn partially_bridged_overture_road_is_split_in_the_archive() {
let roads = build(&[Segment {
id: "road",
subtype: "road",
class: "motorway",
line: [(-0.2, 51.5), (0.2, 51.5)],
flags: vec![("is_bridge", Some((0.2, 0.5)))],
}]);
let z12: Vec<_> = roads.iter().filter(|r| r.zoom == 12).collect();
assert!(z12.iter().all(|r| r.kind == "highway"), "{z12:?}");
assert!(z12.iter().any(|r| r.bridge), "no bridge piece: {z12:?}");
assert!(
z12.iter().any(|r| !r.bridge),
"whole road marked bridge: {z12:?}"
);
assert!(roads.iter().any(|r| r.zoom == 3 && r.kind == "highway"));
assert!(!roads.iter().any(|r| r.zoom < 3));
}
#[test]
fn overture_rail_is_rail_in_the_archive() {
let roads = build(&[Segment {
id: "rail",
subtype: "rail",
class: "standard_gauge",
line: [(-0.2, 51.45), (0.2, 51.55)],
flags: vec![("is_bridge", None)],
}]);
assert!(!roads.is_empty());
assert!(
roads.iter().all(|r| r.kind == "rail" && r.zoom >= 11),
"{roads:?}"
);
assert!(
roads
.iter()
.all(|r| r.detail.as_deref() == Some("standard_gauge") && r.bridge),
"{roads:?}"
);
assert!(roads.iter().any(|r| r.zoom == 11));
}
fn build_archive(files: &[Vec<Segment>], threads: usize) -> Vec<u8> {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
for (i, rows) in files.iter().enumerate() {
write_segment_file(
&root.join("overture"),
&format!("part-{i:05}.parquet"),
rows,
);
}
rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
let out = root.join("out.pmtiles");
let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
let args = vec![
"geolith".to_string(),
"--data".into(),
arg("overture"),
"--natural-earth".into(),
arg("ne.sqlite"),
"--land-polygons".into(),
arg("land"),
"--water-polygons".into(),
arg("water"),
"--output".into(),
out.to_string_lossy().into_owned(),
"--tmpdir".into(),
arg("tmp"),
"--roads-source".into(),
"overture".into(),
"--no-conflate".into(),
"--bbox".into(),
"-0.3,51.4,0.3,51.6".into(),
"--max-zoom".into(),
"10".into(),
];
let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");
rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build()
.expect("thread pool")
.install(|| geolith_cli::run_with_config(&config))
.expect("pipeline runs");
std::fs::read(&out).expect("archive")
}
fn tied_motorway_files() -> Vec<Vec<Segment>> {
let motorway = |file: usize, k: usize| {
let y = 51.45 + 0.1 * (file * 64 + k) as f64 / 1024.0;
Segment {
id: Box::leak(format!("motorway-{file}-{k}").into_boxed_str()),
subtype: "road",
class: "motorway",
line: [(-0.25, y), (0.25, y + 0.001)],
flags: Vec::new(),
}
};
(0..8)
.map(|file| {
let rows = if file == 0 { 2_000 } else { 1 };
(0..rows).map(|k| motorway(file, k)).collect()
})
.collect()
}
#[test]
fn tile_archive_is_byte_identical_across_runs_and_thread_counts() {
let files = tied_motorway_files();
let serial = build_archive(&files, 1);
let tiles = read_all_tiles(&serial);
assert!(
!roads_in(&tiles).is_empty(),
"fixture produced no roads to order"
);
for (run, threads) in [4, 8, 4, 8].into_iter().enumerate() {
let parallel = build_archive(&files, threads);
let other = read_all_tiles(¶llel);
let differing = tiles
.iter()
.filter(|(id, bytes)| other.get(id) != Some(bytes))
.count();
assert_eq!(
differing,
0,
"run {run} on {threads} threads: {differing} of {} tiles differ",
tiles.len()
);
assert!(
parallel == serial,
"run {run} on {threads} threads: archive bytes differ"
);
}
}
fn boundary_features(tiles: &HashMap<u64, Vec<u8>>) -> Vec<HashMap<String, String>> {
let mut out = Vec::new();
for bytes in tiles.values() {
let tile = proto::Tile::decode(bytes.as_slice()).expect("valid MVT");
for layer in tile.layers.iter().filter(|l| l.name == "boundaries") {
for f in &layer.features {
let mut props = HashMap::new();
for pair in f.tags.chunks(2) {
let value = &layer.values[pair[1] as usize];
let text = value
.string_value
.clone()
.or_else(|| value.bool_value.map(|b| b.to_string()))
.or_else(|| value.int_value.map(|i| i.to_string()))
.or_else(|| value.uint_value.map(|i| i.to_string()))
.or_else(|| value.sint_value.map(|i| i.to_string()))
.unwrap_or_default();
props.insert(layer.keys[pair[0] as usize].clone(), text);
}
out.push(props);
}
}
}
out
}
fn kashmir_build(
bbox: &str,
india_boundary: bool,
) -> Result<HashMap<u64, Vec<u8>>, geolith_cli::CliError> {
kashmir_build_with(
bbox,
india_boundary.then_some("kashmir-soi-boundary.geojson"),
)
}
fn kashmir_build_with(
bbox: &str,
india_boundary: Option<&str>,
) -> Result<HashMap<u64, Vec<u8>>, geolith_cli::CliError> {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
let overture = root.join("overture");
std::fs::create_dir_all(&overture).expect("overture dir");
rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
let out = root.join("out.pmtiles");
let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
let mut args: Vec<String> = [
"geolith",
"--data",
&arg("overture"),
"--natural-earth",
&arg("ne.sqlite"),
"--land-polygons",
&arg("land"),
"--water-polygons",
&arg("water"),
"--output",
&out.to_string_lossy(),
"--tmpdir",
&arg("tmp"),
"--node-store",
&arg("nodes.bin"),
"--no-conflate",
"--osm-pbf",
&fixtures
.join("kashmir-boundaries.osm.pbf")
.to_string_lossy(),
"--bbox",
bbox,
"--max-zoom",
"8",
]
.map(String::from)
.to_vec();
if let Some(file) = india_boundary {
args.push("--india-boundary".into());
args.push(fixtures.join(file).to_string_lossy().into_owned());
}
let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");
geolith_cli::run_with_config(&config)?;
Ok(read_all_tiles(&std::fs::read(&out).expect("archive")))
}
#[test]
fn the_polygon_file_and_the_derived_lines_file_give_the_same_tiles() {
let bbox = "72.5,30.5,80.5,37.5";
let lines = kashmir_build_with(bbox, Some("kashmir-soi-derived-shape.geojson")).expect("lines");
let polygons =
kashmir_build_with(bbox, Some("kashmir-soi-datameet-shape.geojson")).expect("polygons");
assert!(!lines.is_empty());
assert_eq!(lines.len(), polygons.len(), "tile count");
for (id, tile) in &lines {
assert_eq!(polygons.get(id), Some(tile), "tile {id} differs");
}
}
#[test]
fn a_tile_build_refuses_files_that_are_not_the_survey_of_india_map() {
let dir = tempfile::tempdir().expect("tempdir");
let germany = dir.path().join("germany.geojson");
std::fs::write(
&germany,
r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"LineString","coordinates":[[5.8,47.2],[15.1,47.2],[15.1,55.1],[5.8,55.1],[5.8,47.2]]}}]}"#,
)
.expect("write");
let empty = dir.path().join("empty.geojson");
std::fs::write(&empty, "").expect("write");
let projected = dir.path().join("projected.geojson");
std::fs::write(
&projected,
r#"{"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:3857"}},"features":[{"type":"Feature","properties":{},"geometry":{"type":"LineString","coordinates":[[8100000,950000],[8500000,950000],[8500000,4400000],[8100000,950000]]}}]}"#,
)
.expect("write");
for (file, expect) in [
(&germany, "does not reach India"),
(&empty, "the file is empty"),
(&projected, "WGS 84"),
] {
let err = kashmir_build_with("72.5,30.5,80.5,37.5", file.to_str())
.expect_err("the file must be refused");
let text = geolith::error::report(&err);
assert!(text.contains(expect), "{expect}: {text}");
assert!(text.contains(&file.display().to_string()), "{text}");
}
}
#[test]
fn a_tile_build_on_soi_land_needs_the_boundary_lines() {
let err = kashmir_build("72.5,30.5,80.5,37.5", false)
.expect_err("Kashmir without --india-boundary must fail");
assert!(err.to_string().contains("Survey of India"), "{err}");
}
#[test]
fn inside_soi_land_only_indian_division_lines_are_drawn() {
let tiles = kashmir_build("72.5,30.5,80.5,37.5", true).expect("build");
let features = boundary_features(&tiles);
let has = |kind: &str, detail: &str| {
features.iter().any(|p| {
p.get("kind").map(String::as_str) == Some(kind)
&& p.get("kind_detail").map(String::as_str) == Some(detail)
})
};
assert!(
has("region", "4"),
"the Indian region line stays: {features:?}"
);
assert!(has("county", "5"), "a Pakistani line outside India stays");
assert!(has("country", "2"), "the Survey of India line is drawn");
assert!(!has("region", "3"), "the Pakistani region line goes");
assert!(!has("county", "6"), "the Indian line with a claim goes");
assert!(
features.iter().all(|p| !p.contains_key("disputed")
&& !p.contains_key("disputed_by")
&& !p.contains_key("claimed_by")
&& !p.contains_key("__owner")),
"no claim and no private mark in a tile: {features:?}"
);
}
fn write_file_without_geometry(dir: &Path, file: &str) {
let part = dir.join("theme=transportation/type=segment");
std::fs::create_dir_all(&part).expect("partition dir");
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Utf8, true)]));
let batch = RecordBatch::try_new(
schema.clone(),
vec![Arc::new(StringArray::from(vec![Some("a")]))],
)
.expect("batch");
let out = std::fs::File::create(part.join(file)).expect("create");
let mut writer = ArrowWriter::try_new(out, schema, None).expect("writer");
writer.write(&batch).expect("write");
writer.close().expect("close");
}
fn run_with_reclaim(more_sources: &dyn Fn(&Path)) -> (tempfile::TempDir, Result<(), String>) {
run_london(
more_sources,
&|_| {},
&["--reclaim-source-after-read", "--allow-missing-type"],
)
}
#[test]
fn reclaim_stops_on_a_data_folder_that_lacks_a_type_and_keeps_the_files() {
let (dir, result) = run_london(&|_| {}, &|_| {}, &["--reclaim-source-after-read"]);
let err = result.expect_err("a type is missing");
assert!(err.contains("holds no Parquet file of"), "{err}");
assert!(err.contains("buildings/building"), "{err}");
assert!(err.contains("--allow-missing-type"), "{err}");
assert!(
!err.contains("transportation/segment"),
"the type that is there is not named: {err}"
);
let road = dir
.path()
.join("overture/theme=transportation/type=segment/part-00000.parquet");
assert!(road.exists(), "the source file is kept");
}
#[test]
fn a_data_folder_that_lacks_a_type_still_builds_without_the_reclaim_flag() {
let (_dir, result) = run_london(&|_| {}, &|_| {}, &[]);
result.expect("builds");
}
fn run_london(
more_sources: &dyn Fn(&Path),
before: &dyn Fn(&Path),
extra: &[&str],
) -> (tempfile::TempDir, Result<(), String>) {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
let rows = [Segment {
id: "a",
subtype: "road",
class: "motorway",
line: [(-0.1, 51.5), (0.1, 51.5)],
flags: vec![],
}];
write_segments(&root.join("overture"), &rows);
more_sources(&root.join("overture"));
rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
before(root);
let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
let mut args: Vec<String> = vec![
"geolith".to_string(),
"--data".into(),
arg("overture"),
"--natural-earth".into(),
arg("ne.sqlite"),
"--land-polygons".into(),
arg("land"),
"--water-polygons".into(),
arg("water"),
"--output".into(),
arg("out.pmtiles"),
"--tmpdir".into(),
arg("tmp"),
"--no-conflate".into(),
"--roads-source".into(),
"overture".into(),
"--bbox".into(),
"-0.3,51.4,0.3,51.6".into(),
"--max-zoom".into(),
"8".into(),
];
args.extend(extra.iter().map(|a| (*a).to_string()));
let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");
let result = geolith_cli::run_with_config(&config).map_err(|e| geolith_cli::error::report(&e));
(dir, result)
}
fn segment_dir(dir: &tempfile::TempDir) -> std::path::PathBuf {
dir.path()
.join("overture/theme=transportation/type=segment")
}
#[test]
fn a_file_that_gave_features_is_reclaimed() {
let (dir, result) = run_with_reclaim(&|_| {});
result.expect("the build succeeds");
assert!(
!segment_dir(&dir).join("part-00000.parquet").exists(),
"a source that was read in full is deleted"
);
}
#[test]
fn a_file_without_a_geometry_column_stops_the_build_and_is_kept() {
let (dir, result) = run_with_reclaim(&|overture| {
write_file_without_geometry(overture, "part-bad.parquet");
});
let error = result.expect_err("the build stops");
assert!(error.contains("part-bad.parquet"), "{error}");
assert!(error.contains("geometry"), "{error}");
assert!(
segment_dir(&dir).join("part-bad.parquet").exists(),
"a file that could not be read is never deleted"
);
}
#[test]
fn a_file_that_gave_no_feature_is_kept() {
let (dir, result) = run_with_reclaim(&|overture| {
write_segment_file(overture, "part-empty.parquet", &[]);
});
result.expect("an empty file is not an error");
assert!(
segment_dir(&dir).join("part-empty.parquet").exists(),
"a file with zero features is kept"
);
assert!(
!segment_dir(&dir).join("part-00000.parquet").exists(),
"the good file is still reclaimed"
);
}
#[test]
fn a_build_removes_its_own_sort_files_and_leaves_the_rest_of_tmpdir() {
let (dir, result) = run_london(
&|_| {},
&|root| {
let tmp = root.join("tmp");
std::fs::create_dir_all(tmp.join("keep-dir")).expect("dir");
std::fs::write(tmp.join("keep.txt"), b"not geolith's").expect("write");
std::fs::write(tmp.join("keep-dir/inner.txt"), b"inner").expect("write");
},
&[],
);
result.expect("the build succeeds");
let tmp = dir.path().join("tmp");
assert_eq!(
std::fs::read(tmp.join("keep.txt")).expect("kept"),
b"not geolith's"
);
assert!(tmp.join("keep-dir/inner.txt").exists());
let mut names: Vec<String> = std::fs::read_dir(&tmp)
.expect("tmpdir is still there")
.map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
.collect();
names.sort();
assert_eq!(names, ["keep-dir", "keep.txt"], "no sort run, no marker");
}
#[test]
fn a_build_removes_a_tmpdir_it_created_itself() {
let (dir, result) = run_london(&|_| {}, &|_| {}, &[]);
result.expect("the build succeeds");
assert!(!dir.path().join("tmp").exists());
}
fn archive_attribution(archive: &[u8]) -> String {
let (offset, length) = (u64_at(archive, 24) as usize, u64_at(archive, 32) as usize);
let json = decompress(&archive[offset..offset + length], archive[97]);
let metadata: serde_json::Value = serde_json::from_slice(&json).expect("metadata JSON");
metadata["attribution"]
.as_str()
.expect("attribution")
.to_owned()
}
#[test]
fn a_tile_archive_credits_the_data_the_build_read() {
let (dir, result) = run_london(&|_| {}, &|_| {}, &[]);
result.expect("the build succeeds");
let attribution = archive_attribution(&std::fs::read(dir.path().join("out.pmtiles")).unwrap());
assert!(
attribution.contains("© OpenStreetMap contributors (ODbL)</a>, Overture Maps Foundation, Natural Earth (public domain)"),
"{attribution}"
);
assert!(
!attribution.contains("DataMeet"),
"no India boundary was read: {attribution}"
);
assert!(attribution.ends_with("| © geolith"), "{attribution}");
}
#[test]
fn a_tile_archive_built_with_the_india_boundary_credits_datameet() {
let boundary = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/kashmir-soi-boundary.geojson")
.to_string_lossy()
.into_owned();
let (dir, result) = run_london(&|_| {}, &|_| {}, &["--india-boundary", &boundary]);
result.expect("the build succeeds");
let attribution = archive_attribution(&std::fs::read(dir.path().join("out.pmtiles")).unwrap());
assert!(
attribution.contains(
"Natural Earth (public domain) | India boundary: DataMeet India community (CC BY 4.0) | © geolith"
),
"{attribution}"
);
}