crates/korp-map-wire/tests/files.rs
//! **The file downloads** (`/v1/files/…`) on a running server: the listing, byte-exact
//! ranges, `HEAD`, `416`, conditional requests, no content encoding, and that nothing but
//! the listed files can be reached. One test has DuckDB read a GeoParquet 2.0 file over
//! HTTP (it needs Python with `duckdb`; see its note).
mod common;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use bytes::Bytes;
use common::Reply;
use http_body_util::{BodyExt, Empty};
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use korp_map_wire::ServerConfig;
use korp_map_wire::files::{FileInfo, FileShelf};
/// The GeoParquet 2.0 fixture: 6000 small rectangles around Stockholm, three row
/// groups, a `bbox` covering column (written by DuckDB 2.0 with `GEOPARQUET_VERSION 'V2'`).
fn fixture_dir() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/geoparquet2")
}
/// Bytes that are not a pattern a wrong offset could match by chance.
fn noise(n: usize) -> Vec<u8> {
let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
(0..n)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
(x >> 24) as u8
})
.collect()
}
struct FileServer {
base: String,
shelf: Arc<FileShelf>,
big: Vec<u8>,
_tmp: tempfile::TempDir,
}
/// A server with two sets of region `testland`: `geoparquet2` (the fixture) and `raw`
/// (one 3 MB file of noise, `big.parquet`, and `PAR1.parquet`).
async fn start(hash: bool) -> FileServer {
let tmp = tempfile::tempdir().unwrap();
let raw = tmp.path().join("raw");
std::fs::create_dir(&raw).unwrap();
let big = noise(3_000_000 + 17);
std::fs::write(raw.join("big.parquet"), &big).unwrap();
std::fs::write(raw.join("PAR1.parquet"), b"PAR1").unwrap();
std::fs::write(tmp.path().join("secret.parquet"), b"not served").unwrap();
let mut shelf = FileShelf::new();
shelf
.add(&format!("testland={}", fixture_dir().display()))
.unwrap();
shelf
.add(&format!("testland:raw={}", raw.display()))
.unwrap();
if hash {
shelf.hash_all(|_, r| assert!(r.is_ok()));
}
let shelf = Arc::new(shelf);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let cfg = ServerConfig {
files: shelf.clone(),
..ServerConfig::default()
};
let region = common::write_region(tmp.path());
let source = Arc::new(korp_map_wire::FileSource::open_dir(®ion).unwrap());
tokio::spawn(async move { korp_map_wire::serve(listener, source, cfg).await });
FileServer {
base: format!("http://{addr}"),
shelf,
big,
_tmp: tmp,
}
}
async fn send(method: &str, url: &str, headers: &[(&str, &str)]) -> Reply {
let client = Client::builder(TokioExecutor::new()).build_http::<Empty<Bytes>>();
let mut req = http::Request::builder().method(method).uri(url);
for (k, v) in headers {
req = req.header(*k, *v);
}
let res = client
.request(req.body(Empty::new()).unwrap())
.await
.unwrap();
let status = res.status().as_u16();
let headers = res.headers().clone();
let body = res.into_body().collect().await.unwrap().to_bytes();
Reply {
status,
headers,
body,
}
}
const BIG: &str = "/v1/files/testland/raw/big.parquet";
#[tokio::test(flavor = "multi_thread")]
async fn the_listing_names_every_file_with_its_format_size_and_sha256() {
let s = start(true).await;
let r = send("GET", &format!("{}/v1/files/testland/", s.base), &[]).await;
assert_eq!(r.status, 200);
assert_eq!(r.header("content-type"), Some("application/json"));
let rows: Vec<FileInfo> = serde_json::from_slice(&r.body).unwrap();
let names: Vec<String> = rows
.iter()
.map(|f| format!("{}/{} {}", f.set, f.name, f.format))
.collect();
assert_eq!(
names,
[
"geoparquet2/areas.parquet geoparquet-2.0",
"raw/PAR1.parquet parquet",
"raw/big.parquet parquet",
]
);
let big = rows.iter().find(|f| f.name == "big.parquet").unwrap();
assert_eq!(big.size, s.big.len() as u64);
assert_eq!(big.url, BIG);
assert_eq!(big.sha256.as_deref(), Some(sha256(&s.big).as_str()));
let fixture = std::fs::read(fixture_dir().join("areas.parquet")).unwrap();
assert_eq!(rows[0].sha256.as_deref(), Some(sha256(&fixture).as_str()));
// Every region, and the same without the trailing slash.
let all = send("GET", &format!("{}/v1/files/", s.base), &[]).await;
assert_eq!(all.body, r.body);
let bare = send("GET", &format!("{}/v1/files/testland", s.base), &[]).await;
assert_eq!(bare.body, r.body);
let head = send("HEAD", &format!("{}/v1/files/testland/", s.base), &[]).await;
assert_eq!(head.status, 200);
assert!(head.body.is_empty());
let none = send("GET", &format!("{}/v1/files/elsewhere/", s.base), &[]).await;
assert_eq!(none.status, 404);
assert_eq!(none.json()["code"], "korp-map-124");
}
fn sha256(b: &[u8]) -> String {
use sha2::Digest;
sha2::Sha256::digest(b)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn a_whole_file_comes_byte_exact_with_its_headers_and_unencoded() {
let s = start(true).await;
let url = format!("{}{BIG}", s.base);
let r = send("GET", &url, &[("accept-encoding", "zstd, br, gzip")]).await;
assert_eq!(r.status, 200);
assert_eq!(r.body.as_ref(), s.big.as_slice());
assert_eq!(
r.header("content-type"),
Some("application/vnd.apache.parquet")
);
assert_eq!(r.header("accept-ranges"), Some("bytes"));
assert_eq!(
r.header("content-length"),
Some(s.big.len().to_string().as_str())
);
assert_eq!(
r.header("content-encoding"),
None,
"Parquet is sent as it is"
);
assert_eq!(
r.header("etag"),
Some(format!("\"{}\"", sha256(&s.big)).as_str())
);
assert!(r.header("last-modified").unwrap().ends_with(" GMT"));
assert_eq!(r.header("access-control-allow-origin"), Some("*"));
let head = send("HEAD", &url, &[]).await;
assert_eq!(head.status, 200);
assert!(head.body.is_empty());
assert_eq!(
head.header("content-length"),
Some(s.big.len().to_string().as_str())
);
assert_eq!(head.header("etag"), r.header("etag"));
let again = send("GET", &url, &[("if-none-match", r.header("etag").unwrap())]).await;
assert_eq!(again.status, 304);
assert!(again.body.is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn ranges_are_byte_exact() {
let s = start(false).await;
let url = format!("{}{BIG}", s.base);
let n = s.big.len();
for (range, from, to) in [
("bytes=0-3", 0, 3),
("bytes=1000000-2500000", 1_000_000, 2_500_000),
(&format!("bytes={}-", n - 10) as &str, n - 10, n - 1),
("bytes=-8", n - 8, n - 1),
(&format!("bytes=5-{}", n + 1000) as &str, 5, n - 1),
] {
let r = send("GET", &url, &[("range", range)]).await;
assert_eq!(r.status, 206, "{range}");
assert_eq!(r.body.as_ref(), &s.big[from..=to], "{range}");
assert_eq!(
r.header("content-range"),
Some(format!("bytes {from}-{to}/{n}").as_str()),
"{range}"
);
assert_eq!(
r.header("content-length"),
Some((to - from + 1).to_string().as_str())
);
let head = send("HEAD", &url, &[("range", range)]).await;
assert_eq!(head.status, 206);
assert!(head.body.is_empty());
assert_eq!(head.header("content-range"), r.header("content-range"));
}
let par1 = send(
"GET",
&format!("{}/v1/files/testland/raw/PAR1.parquet", s.base),
&[("range", "bytes=0-3")],
)
.await;
assert_eq!(par1.body.as_ref(), b"PAR1");
}
#[tokio::test(flavor = "multi_thread")]
async fn several_ranges_come_as_multipart_byteranges() {
let s = start(false).await;
let r = send(
"GET",
&format!("{}{BIG}", s.base),
&[("range", "bytes=0-9,100-199")],
)
.await;
assert_eq!(r.status, 206);
let ct = r.header("content-type").unwrap();
assert!(ct.starts_with("multipart/byteranges; boundary="), "{ct}");
let boundary = ct.split("boundary=").nth(1).unwrap();
assert_eq!(
r.header("content-length"),
Some(r.body.len().to_string().as_str())
);
let body = r.body.as_ref();
let mut parts = Vec::new();
let sep = format!("\r\n--{boundary}");
let mut at = 0;
while let Some(i) = find(&body[at..], sep.as_bytes()) {
at += i + sep.len();
if body[at..].starts_with(b"--") {
break;
}
let head_end = find(&body[at..], b"\r\n\r\n").unwrap();
let head = std::str::from_utf8(&body[at..at + head_end])
.unwrap()
.to_string();
let start = at + head_end + 4;
let len = find(&body[start..], sep.as_bytes()).unwrap();
parts.push((head, body[start..start + len].to_vec()));
at = start + len;
}
assert_eq!(parts.len(), 2);
let n = s.big.len();
assert!(
parts[0]
.0
.contains(&format!("Content-Range: bytes 0-9/{n}"))
);
assert_eq!(parts[0].1, &s.big[0..10]);
assert!(
parts[1]
.0
.contains(&format!("Content-Range: bytes 100-199/{n}"))
);
assert_eq!(parts[1].1, &s.big[100..200]);
}
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
hay.windows(needle.len()).position(|w| w == needle)
}
#[tokio::test(flavor = "multi_thread")]
async fn a_range_past_the_end_is_416_and_a_changed_validator_sends_the_whole_file() {
let s = start(true).await;
let url = format!("{}{BIG}", s.base);
let n = s.big.len();
let r = send("GET", &url, &[("range", &format!("bytes={n}-") as &str)]).await;
assert_eq!(r.status, 416);
assert_eq!(
r.header("content-range"),
Some(format!("bytes */{n}").as_str())
);
assert_eq!(r.json()["code"], "korp-map-125");
// A range this server cannot read (another unit, bad syntax) is the whole file.
for ignored in ["items=0-1", "bytes=9-2", "bytes=abc"] {
let r = send("GET", &url, &[("range", ignored)]).await;
assert_eq!(r.status, 200, "{ignored}");
assert_eq!(r.body.len(), n);
}
// If-Range: the range only for this very file.
let etag = format!("\"{}\"", sha256(&s.big));
let held = send("GET", &url, &[("range", "bytes=0-3"), ("if-range", &etag)]).await;
assert_eq!(held.status, 206);
let changed = send(
"GET",
&url,
&[("range", "bytes=0-3"), ("if-range", "\"0000\"")],
)
.await;
assert_eq!(changed.status, 200);
assert_eq!(changed.body.len(), n);
}
#[tokio::test(flavor = "multi_thread")]
async fn only_the_listed_files_can_be_reached() {
let s = start(false).await;
for path in [
"/v1/files/testland/raw/secret.parquet",
"/v1/files/testland/raw/..%2Fsecret.parquet",
"/v1/files/testland/raw/%2E%2E%2Fsecret.parquet",
"/v1/files/testland/..%2F..%2Fraw/big.parquet",
"/v1/files/testland/geoparquet2/..%2Fraw%2Fbig.parquet",
"/v1/files/testland/raw/big.parquet%00",
"/v1/files/testland/raw/BIG.parquet",
"/v1/files/elsewhere/raw/big.parquet",
] {
let r = send("GET", &format!("{}{path}", s.base), &[]).await;
assert_eq!(r.status, 404, "{path}");
assert_eq!(r.json()["code"], "korp-map-124", "{path}");
}
for path in [
"/v1/files/testland/raw/../../secret.parquet",
"/v1/files/testland/raw/big.parquet/x",
"/v1/files/testland/raw",
] {
let r = send("GET", &format!("{}{path}", s.base), &[]).await;
assert_eq!(r.status, 404, "{path}");
}
let post = send("POST", &format!("{}{BIG}", s.base), &[]).await;
assert_eq!(post.status, 405);
assert_eq!(post.header("allow"), Some("GET, HEAD, OPTIONS"));
assert!(s.shelf.get("testland", "raw", "big.parquet").is_some());
}
#[tokio::test(flavor = "multi_thread")]
async fn a_file_changed_on_disk_is_refused() {
let s = start(false).await;
let path = s
.shelf
.get("testland", "raw", "big.parquet")
.unwrap()
.path
.clone();
std::fs::write(&path, b"shorter now").unwrap();
let r = send("GET", &format!("{}{BIG}", s.base), &[]).await;
assert_eq!(r.status, 503);
assert_eq!(r.json()["code"], "korp-map-126");
}
#[tokio::test(flavor = "multi_thread")]
async fn the_landing_page_lists_the_files_with_a_duckdb_example() {
let s = start(true).await;
let r = send("GET", &format!("{}/v1/", s.base), &[]).await;
let html = String::from_utf8(r.body.to_vec()).unwrap();
assert!(html.contains("href=\"/v1/files/testland/geoparquet2/areas.parquet\""));
assert!(html.contains("FROM 'ORIGIN/v1/files/testland/geoparquet2/areas.parquet'"));
assert!(html.contains("WHERE bbox.xmin <= MAXLON AND bbox.xmax >= MINLON"));
}
/// **DuckDB queries the GeoParquet 2.0 fixture over HTTP** (httpfs + spatial): the
/// same count over the server as from the file, and the server answered range requests.
///
/// Needs a Python with `duckdb` (and network for DuckDB's first `INSTALL httpfs`):
/// `KORP_MAP_PYTHON=<python> cargo test --test files -- --ignored`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "needs KORP_MAP_PYTHON, a Python with duckdb"]
async fn duckdb_reads_a_geoparquet_2_file_over_http() {
let python = std::env::var("KORP_MAP_PYTHON").expect("KORP_MAP_PYTHON");
let s = start(true).await;
let url = format!("{}/v1/files/testland/geoparquet2/areas.parquet", s.base);
let local = fixture_dir().join("areas.parquet");
let script = r#"
import sys, duckdb
url, local = sys.argv[1], sys.argv[2]
con = duckdb.connect()
con.execute("INSTALL httpfs; LOAD httpfs; INSTALL spatial; LOAD spatial;")
where = "bbox.xmin <= 18.0 AND bbox.xmax >= 17.95 AND bbox.ymin <= 59.25 AND bbox.ymax >= 59.22"
for src in (url, local):
n = con.execute(f"SELECT count(*) FROM '{src}' WHERE {where}").fetchone()[0]
m = con.execute(f"SELECT count(*) FROM '{src}' WHERE ST_Intersects(geometry, ST_MakeEnvelope(17.95, 59.22, 18.0, 59.25))").fetchone()[0]
t = con.execute(f"SELECT typeof(geometry) FROM '{src}' LIMIT 1").fetchone()[0]
print(n, m, t)
"#;
let out = tokio::process::Command::new(&python)
.arg("-c")
.arg(script)
.arg(&url)
.arg(&local)
.output()
.await
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
out.status.success(),
"{stdout}\n{}",
String::from_utf8_lossy(&out.stderr)
);
let lines: Vec<&str> = stdout.lines().collect();
assert_eq!(lines.len(), 2, "{stdout}");
assert_eq!(lines[0], lines[1], "over HTTP and from the file");
let n: u64 = lines[0].split(' ').next().unwrap().parse().unwrap();
assert!(n > 100, "{stdout}");
assert!(lines[0].contains("GEOMETRY"), "{stdout}");
}