Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/src/files.rs

//! **A region's Parquet files, served for download and remote querying**
//! (`/v1/files/…`).
//!
//! `korp-map-server --files <region>[:<set>]=<dir>` (repeatable) puts every `*.parquet`
//! file directly in `<dir>` on the shelf under `/v1/files/<region>/<set>/<file>`. Without
//! `:<set>`, the set is named by the files' format: `native` (GeoParquet 1.1 native
//! encodings, as osm-katana's native export writes them), `geoparquet2` (GeoParquet 2.0,
//! the Parquet `GEOMETRY` type) or `parquet`.
//!
//! * `GET /v1/files/` and `GET /v1/files/<region>/` list the files as a JSON array of
//!   [`FileInfo`]: name, format, size, sha256, url, region, set and last_modified.
//! * `GET` and `HEAD /v1/files/<region>/<set>/<file>` serve one file with HTTP range
//!   requests (one range, or several as `multipart/byteranges`), `Accept-Ranges`,
//!   `Content-Length`, `Last-Modified`, `ETag` (the sha256), `If-None-Match`,
//!   `If-Range`, `206` and `416`. The bytes are read from disk as they are sent, never
//!   whole into memory, and never content-encoded (Parquet pages are compressed
//!   already).
//!
//! Only the files on the shelf are served: a request names a region, a set and a file
//! name, each looked up exactly in the shelf, so no path is ever built from a request.
//! A file that changed on disk since the start (another size or time) is refused,
//! because its listed size and sha256 would be wrong.
//!
//! The sha256 of every file is computed once, by [`FileShelf::hash_all`] (the server runs
//! it in the background at start); until a file's is known its listing says `null` and
//! its replies carry no `ETag`.

use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};

use bytes::Bytes;
use http::{HeaderMap, HeaderValue, Response, StatusCode, header};
use http_body_util::BodyExt;
use serde::Serialize;
use std::sync::Arc;

use crate::error::{Code, WireError};
use crate::http::{Body, BoxError, ChannelBody, error_response, full};

/// The media type of a Parquet file.
pub const PARQUET_TYPE: &str = "application/vnd.apache.parquet";

/// One served file.
#[derive(Debug)]
pub struct ServedFile {
    /// The file name (the last path segment of its URL).
    pub name: String,
    /// Where it is on disk.
    pub path: PathBuf,
    /// Its size at start.
    pub size: u64,
    /// Its modification time at start.
    pub modified: SystemTime,
    /// `geoparquet-1.1-native`, `geoparquet-2.0`, `geoparquet-1.x` or `parquet`.
    pub format: String,
    sha256: OnceLock<String>,
}

impl ServedFile {
    /// The sha256 (lower-case hex), once [`FileShelf::hash_all`] has reached this file.
    #[must_use]
    pub fn sha256(&self) -> Option<&str> {
        self.sha256.get().map(String::as_str)
    }

    /// Is the file on disk still the one listed (same size and time)?
    #[must_use]
    pub fn unchanged(&self) -> bool {
        std::fs::metadata(&self.path)
            .ok()
            .is_some_and(|m| m.len() == self.size && m.modified().ok() == Some(self.modified))
    }
}

/// The files of one `--files` flag.
#[derive(Debug)]
pub struct FileSet {
    /// The region they belong to.
    pub region: String,
    /// The set name (the URL segment after the region).
    pub name: String,
    /// The directory they are in.
    pub dir: PathBuf,
    /// The files, by name.
    pub files: Vec<ServedFile>,
}

/// One row of a file listing.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, serde::Deserialize)]
pub struct FileInfo {
    /// The region.
    pub region: String,
    /// The set.
    pub set: String,
    /// The file name.
    pub name: String,
    /// The format (see [`ServedFile::format`]).
    pub format: String,
    /// Bytes.
    pub size: u64,
    /// Lower-case hex, or `null` while it is being computed.
    pub sha256: Option<String>,
    /// HTTP date.
    pub last_modified: String,
    /// The path to fetch it from on this server.
    pub url: String,
}

/// **Every file the server serves under `/v1/files/`.**
#[derive(Debug, Default)]
pub struct FileShelf {
    sets: Vec<FileSet>,
}

/// A name usable as one URL segment as it is: letters, digits, `.`, `_` and `-`, not
/// starting with a dot.
fn plain_segment(s: &str) -> bool {
    !s.is_empty()
        && !s.starts_with('.')
        && s.bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
}

impl FileShelf {
    /// An empty shelf.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Nothing is served.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.sets.iter().all(|s| s.files.is_empty())
    }

    /// The sets, in the order they were added.
    #[must_use]
    pub fn sets(&self) -> &[FileSet] {
        &self.sets
    }

    /// **Add the files of `--files <region>[:<set>]=<dir>`.** Every `*.parquet` regular
    /// file (or link to one) directly in `<dir>`, in name order. Refused: a bad spec, a
    /// directory that cannot be read or holds no Parquet file, a file name that is not a
    /// plain URL segment, a set already on the shelf, and no `:<set>` for files of mixed
    /// formats.
    pub fn add(&mut self, spec: &str) -> Result<&FileSet, String> {
        let Some((name, dir)) = spec.split_once('=') else {
            return Err(format!("--files {spec:?}: expected <region>[:<set>]=<dir>"));
        };
        let (region, set) = match name.split_once(':') {
            Some((r, s)) => (r, Some(s)),
            None => (name, None),
        };
        for (what, v) in [("region", Some(region)), ("set", set)] {
            if let Some(v) = v
                && !plain_segment(v)
            {
                return Err(format!(
                    "--files {spec:?}: the {what} {v:?} must be letters, digits, '.', '_' or '-'"
                ));
            }
        }
        let dir = PathBuf::from(dir);
        let entries = std::fs::read_dir(&dir)
            .map_err(|e| format!("--files {spec:?}: {}: {e}", dir.display()))?;
        let mut files = Vec::new();
        for entry in entries {
            let entry = entry.map_err(|e| format!("--files {spec:?}: {}: {e}", dir.display()))?;
            let name = entry.file_name().to_string_lossy().into_owned();
            if !name.ends_with(".parquet") {
                continue;
            }
            let path = entry.path();
            let meta = std::fs::metadata(&path)
                .map_err(|e| format!("--files {spec:?}: {}: {e}", path.display()))?;
            if !meta.is_file() {
                continue;
            }
            if !plain_segment(&name) {
                return Err(format!(
                    "--files {spec:?}: the file name {name:?} is not a plain URL segment"
                ));
            }
            files.push(ServedFile {
                format: format_of(&path),
                modified: meta
                    .modified()
                    .map_err(|e| format!("--files {spec:?}: {}: {e}", path.display()))?,
                size: meta.len(),
                path,
                name,
                sha256: OnceLock::new(),
            });
        }
        if files.is_empty() {
            return Err(format!(
                "--files {spec:?}: {} holds no .parquet file",
                dir.display()
            ));
        }
        files.sort_by(|a, b| a.name.cmp(&b.name));
        let set = match set {
            Some(s) => s.to_string(),
            None => {
                let first = &files[0].format;
                if files.iter().any(|f| &f.format != first) {
                    return Err(format!(
                        "--files {spec:?}: the files are of more than one format; name the set \
                         (--files {region}:<set>={})",
                        dir.display()
                    ));
                }
                default_set_name(first).to_string()
            }
        };
        if self.find_set(region, &set).is_some() {
            return Err(format!(
                "--files {spec:?}: the set {region}/{set} is already served"
            ));
        }
        self.sets.push(FileSet {
            region: region.to_string(),
            name: set,
            dir,
            files,
        });
        Ok(self.sets.last().expect("just pushed"))
    }

    fn find_set(&self, region: &str, set: &str) -> Option<&FileSet> {
        self.sets
            .iter()
            .find(|s| s.region == region && s.name == set)
    }

    /// The file `/v1/files/<region>/<set>/<file>` names, if it is on the shelf.
    #[must_use]
    pub fn get(&self, region: &str, set: &str, file: &str) -> Option<&ServedFile> {
        self.find_set(region, set)?
            .files
            .iter()
            .find(|f| f.name == file)
    }

    /// The listing of `region` (every region when `None`); `None` when the region has
    /// no files here.
    #[must_use]
    pub fn listing(&self, region: Option<&str>) -> Option<Vec<FileInfo>> {
        let rows: Vec<FileInfo> = self
            .sets
            .iter()
            .filter(|s| region.is_none_or(|r| s.region == r))
            .flat_map(|s| {
                s.files.iter().map(move |f| FileInfo {
                    region: s.region.clone(),
                    set: s.name.clone(),
                    name: f.name.clone(),
                    format: f.format.clone(),
                    size: f.size,
                    sha256: f.sha256().map(str::to_string),
                    last_modified: http_date(f.modified),
                    url: format!("/v1/files/{}/{}/{}", s.region, s.name, f.name),
                })
            })
            .collect();
        (region.is_none() || !rows.is_empty()).then_some(rows)
    }

    /// **Compute every file's sha256** (blocking; run it on a thread of its own).
    /// `done` hears each file's result. A file that cannot be read keeps no sha256.
    pub fn hash_all(&self, mut done: impl FnMut(&ServedFile, Result<&str, String>)) {
        for set in &self.sets {
            for f in &set.files {
                match sha256_of(&f.path) {
                    Ok(h) => {
                        let _ = f.sha256.set(h);
                        done(f, Ok(f.sha256().unwrap_or_default()));
                    }
                    Err(e) => done(f, Err(e)),
                }
            }
        }
    }
}

fn default_set_name(format: &str) -> &'static str {
    match format {
        "geoparquet-1.1-native" => "native",
        "geoparquet-2.0" => "geoparquet2",
        "geoparquet-1.x" => "geoparquet1",
        _ => "parquet",
    }
}

/// The sha256 of the file at `path`, lower-case hex, read in 1 MiB pieces.
pub fn sha256_of(path: &Path) -> Result<String, String> {
    use sha2::Digest;
    use std::io::Read;
    let mut f = File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
    let mut h = sha2::Sha256::new();
    let mut buf = vec![0u8; 1 << 20];
    loop {
        let n = f
            .read(&mut buf)
            .map_err(|e| format!("{}: {e}", path.display()))?;
        if n == 0 {
            break;
        }
        h.update(&buf[..n]);
    }
    Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
}

/// The file's format, from its Parquet footer: the `geo` metadata's version and the
/// primary column's encoding.
#[must_use]
pub fn format_of(path: &Path) -> String {
    let geo = File::open(path)
        .ok()
        .and_then(|f| {
            parquet::file::metadata::ParquetMetaDataReader::new()
                .parse_and_finish(&f)
                .ok()
        })
        .and_then(|m| {
            m.file_metadata()
                .key_value_metadata()?
                .iter()
                .find(|kv| kv.key == "geo")?
                .value
                .clone()
        })
        .and_then(|v| serde_json::from_str::<serde_json::Value>(&v).ok());
    let Some(geo) = geo else {
        return "parquet".to_string();
    };
    let version = geo["version"].as_str().unwrap_or("");
    let primary = geo["primary_column"].as_str().unwrap_or("geometry");
    let encoding = geo["columns"][primary]["encoding"].as_str().unwrap_or("");
    if version.starts_with("2.") {
        "geoparquet-2.0".to_string()
    } else if version.starts_with("1.1")
        && !encoding.eq_ignore_ascii_case("wkb")
        && !encoding.is_empty()
    {
        "geoparquet-1.1-native".to_string()
    } else {
        "geoparquet-1.x".to_string()
    }
}

/// `t` as an HTTP date (IMF-fixdate), e.g. `Sun, 06 Nov 1994 08:49:37 GMT`.
#[must_use]
pub fn http_date(t: SystemTime) -> String {
    let secs = t
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs() as i64);
    let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
    // Civil date from days since 1970-01-01 (H. Hinnant's algorithm).
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i64::from(month <= 2);
    const WEEKDAY: [&str; 7] = ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"];
    const MONTH: [&str; 12] = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ];
    format!(
        "{}, {day:02} {} {year} {:02}:{:02}:{:02} GMT",
        WEEKDAY[days.rem_euclid(7) as usize],
        MONTH[(month - 1) as usize],
        rem / 3600,
        rem / 60 % 60,
        rem % 60
    )
}

/// What a `Range` header asks of a file of `size` bytes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Ranges {
    /// No range, or one to ignore (another unit, bad syntax, too many): the whole file.
    Whole,
    /// These byte ranges, `start..=end`, each within the file, in the order asked.
    Parts(Vec<(u64, u64)>),
    /// Well-formed, but no range overlaps the file: `416`.
    Unsatisfiable,
}

/// At most this many ranges in one request; more are ignored (the whole file).
pub const MAX_RANGES: usize = 32;

/// **Read a `Range` header** (RFC 9110 §14): `bytes=a-b`, `bytes=a-`, `bytes=-n`, comma
/// separated. A range starting past the end is dropped; when none is left the answer is
/// [`Ranges::Unsatisfiable`].
#[must_use]
pub fn parse_range(header: &str, size: u64) -> Ranges {
    let Some(spec) = header.trim().strip_prefix("bytes=") else {
        return Ranges::Whole;
    };
    let specs: Vec<&str> = spec.split(',').map(str::trim).collect();
    if specs.is_empty() || specs.len() > MAX_RANGES {
        return Ranges::Whole;
    }
    let mut parts = Vec::new();
    for s in specs {
        let Some((a, b)) = s.split_once('-') else {
            return Ranges::Whole;
        };
        let num = |v: &str| v.parse::<u64>().ok();
        match (a.is_empty(), b.is_empty()) {
            (true, true) => return Ranges::Whole,
            (true, false) => {
                let Some(n) = num(b) else {
                    return Ranges::Whole;
                };
                if n > 0 && size > 0 {
                    parts.push((size.saturating_sub(n), size - 1));
                }
            }
            (false, _) => {
                let Some(start) = num(a) else {
                    return Ranges::Whole;
                };
                let end = if b.is_empty() {
                    u64::MAX
                } else {
                    match num(b) {
                        Some(e) if e >= start => e,
                        _ => return Ranges::Whole,
                    }
                };
                if start < size {
                    parts.push((start, end.min(size - 1)));
                }
            }
        }
    }
    if parts.is_empty() {
        Ranges::Unsatisfiable
    } else {
        Ranges::Parts(parts)
    }
}

// ── The HTTP side ──────────────────────────────────────────────────────────────────

/// The boundary of a `multipart/byteranges` reply.
const BOUNDARY: &str = "korp-map-byteranges";
/// Bytes read from disk per frame.
const CHUNK: usize = 256 * 1024;

/// A piece of a file reply: bytes as they are, or a byte range of the file.
enum Piece {
    Text(Bytes),
    Range(u64, u64),
}

/// The JSON listing of `region` (every region when `None`), or the refusal.
pub(crate) fn listing_response(shelf: &FileShelf, region: Option<&str>) -> Response<Body> {
    match shelf.listing(region) {
        Some(rows) => match serde_json::to_vec(&rows) {
            Ok(j) => {
                let mut r = Response::new(full(j));
                r.headers_mut().insert(
                    header::CONTENT_TYPE,
                    HeaderValue::from_static("application/json"),
                );
                r
            }
            Err(e) => error_response(&WireError::new(
                Code::EncodeFailed,
                format!("file listing: {e}"),
            )),
        },
        None => error_response(&WireError::new(
            Code::NoFile,
            format!(
                "no files are served for the region {:?}",
                region.unwrap_or("")
            ),
        )),
    }
}

/// **`GET` or `HEAD` of one file**, with `Range`, `If-Range` and `If-None-Match`.
pub(crate) fn file_response(
    shelf: &Arc<FileShelf>,
    (region, set, name): (&str, &str, &str),
    head: bool,
    headers: &HeaderMap,
    max_age: Option<u32>,
) -> Response<Body> {
    let Some(f) = shelf.get(region, set, name) else {
        return error_response(&WireError::new(
            Code::NoFile,
            format!("no file {region}/{set}/{name} is served; the listing is /v1/files/{region}/"),
        ));
    };
    if !f.unchanged() {
        return error_response(&WireError::new(
            Code::FileChanged,
            format!(
                "{region}/{set}/{name} changed on disk since the server started; its listed size and sha256 no longer hold"
            ),
        ));
    }
    let etag = f.sha256().map(|h| format!("\"{h}\""));
    let last_modified = http_date(f.modified);
    let text = |h: &http::HeaderName| headers.get(h).and_then(|v| v.to_str().ok());
    let mut r = if let (Some(tag), Some(inm)) = (f.sha256(), text(&header::IF_NONE_MATCH))
        && crate::cache::matching(inm, tag).is_some()
    {
        let mut r = Response::new(full(Bytes::new()));
        *r.status_mut() = StatusCode::NOT_MODIFIED;
        r
    } else {
        // `If-Range`: the range holds only for this very file (its tag, or its date).
        let range_holds = text(&header::IF_RANGE)
            .is_none_or(|v| Some(v) == etag.as_deref() || v == last_modified);
        let ranges = match text(&header::RANGE) {
            Some(h) if range_holds => parse_range(h, f.size),
            _ => Ranges::Whole,
        };
        match ranges {
            Ranges::Unsatisfiable => {
                let mut r = error_response(&WireError::new(
                    Code::RangeNotSatisfiable,
                    format!(
                        "no byte of the range is in {region}/{set}/{name} ({} bytes)",
                        f.size
                    ),
                ));
                if let Ok(v) = HeaderValue::from_str(&format!("bytes */{}", f.size)) {
                    r.headers_mut().insert(header::CONTENT_RANGE, v);
                }
                r.headers_mut()
                    .insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
                return r;
            }
            Ranges::Whole => body_of(
                f,
                vec![Piece::Range(0, f.size.saturating_sub(1))],
                200,
                None,
                head,
            ),
            Ranges::Parts(parts) if parts.len() == 1 => {
                let (a, b) = parts[0];
                body_of(
                    f,
                    vec![Piece::Range(a, b)],
                    206,
                    Some(format!("bytes {a}-{b}/{}", f.size)),
                    head,
                )
            }
            Ranges::Parts(parts) => {
                let mut pieces = Vec::new();
                for (a, b) in parts {
                    pieces.push(Piece::Text(Bytes::from(format!(
                        "\r\n--{BOUNDARY}\r\nContent-Type: {PARQUET_TYPE}\r\nContent-Range: bytes {a}-{b}/{}\r\n\r\n",
                        f.size
                    ))));
                    pieces.push(Piece::Range(a, b));
                }
                pieces.push(Piece::Text(Bytes::from(format!("\r\n--{BOUNDARY}--\r\n"))));
                let mut r = body_of(f, pieces, 206, None, head);
                if let Ok(v) =
                    HeaderValue::from_str(&format!("multipart/byteranges; boundary={BOUNDARY}"))
                {
                    r.headers_mut().insert(header::CONTENT_TYPE, v);
                }
                r
            }
        }
    };
    let h = r.headers_mut();
    h.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
    if let Ok(v) = HeaderValue::from_str(&last_modified) {
        h.insert(header::LAST_MODIFIED, v);
    }
    if let Some(v) = etag.and_then(|e| HeaderValue::from_str(&e).ok()) {
        h.insert(header::ETAG, v);
    }
    if let Some(s) = max_age
        && let Ok(v) = HeaderValue::from_str(&format!("public, max-age={s}"))
    {
        h.insert(header::CACHE_CONTROL, v);
    }
    r
}

/// A reply of `pieces` read from `f` as they are sent (empty for `HEAD`), with its
/// `Content-Length`.
fn body_of(
    f: &ServedFile,
    pieces: Vec<Piece>,
    status: u16,
    content_range: Option<String>,
    head: bool,
) -> Response<Body> {
    let len: u64 = pieces
        .iter()
        .map(|p| match p {
            Piece::Text(b) => b.len() as u64,
            Piece::Range(a, b) if f.size > 0 => b - a + 1,
            Piece::Range(..) => 0,
        })
        .sum();
    let body = if head || len == 0 {
        full(Bytes::new())
    } else {
        stream_pieces(f.path.clone(), pieces)
    };
    let mut r = Response::new(body);
    *r.status_mut() = StatusCode::from_u16(status).unwrap_or(StatusCode::OK);
    let h = r.headers_mut();
    h.insert(header::CONTENT_TYPE, HeaderValue::from_static(PARQUET_TYPE));
    h.insert(header::CONTENT_LENGTH, HeaderValue::from(len));
    if let Some(v) = content_range.and_then(|c| HeaderValue::from_str(&c).ok()) {
        h.insert(header::CONTENT_RANGE, v);
    }
    r
}

/// A body that reads `pieces` of the file at `path` on a blocking thread, [`CHUNK`]
/// bytes at a time, as the client takes them (a bounded channel: a slow client holds
/// the reader back, a gone one stops it).
fn stream_pieces(path: PathBuf, pieces: Vec<Piece>) -> Body {
    let (tx, rx) = tokio::sync::mpsc::channel::<Result<Bytes, BoxError>>(4);
    tokio::task::spawn_blocking(move || {
        use std::os::unix::fs::FileExt;
        let file = match File::open(&path) {
            Ok(f) => f,
            Err(e) => {
                let _ = tx.blocking_send(Err(format!("{}: {e}", path.display()).into()));
                return;
            }
        };
        for p in pieces {
            match p {
                Piece::Text(b) => {
                    if tx.blocking_send(Ok(b)).is_err() {
                        return;
                    }
                }
                Piece::Range(a, b) => {
                    let mut at = a;
                    while at <= b {
                        let n = usize::try_from((b - at + 1).min(CHUNK as u64)).unwrap_or(CHUNK);
                        let mut buf = vec![0u8; n];
                        if let Err(e) = file.read_exact_at(&mut buf, at) {
                            let _ =
                                tx.blocking_send(Err(format!("{}: {e}", path.display()).into()));
                            return;
                        }
                        if tx.blocking_send(Ok(Bytes::from(buf))).is_err() {
                            return;
                        }
                        at += n as u64;
                    }
                }
            }
        }
    });
    ChannelBody { rx }.boxed_unsync()
}

/// The landing page's section on the files (empty when none are served).
#[must_use]
pub fn landing_section(shelf: &FileShelf) -> String {
    let Some(rows) = shelf.listing(None).filter(|r| !r.is_empty()) else {
        return String::new();
    };
    let esc = |s: &str| {
        s.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
    };
    let mut table = String::new();
    for r in &rows {
        table.push_str(&format!(
            "<tr><td><a href=\"{url}\">{region}/{set}/{name}</a></td><td>{format}</td><td>{mb:.1} MB</td><td><code>{sha}</code></td></tr>\n",
            url = esc(&r.url),
            region = esc(&r.region),
            set = esc(&r.set),
            name = esc(&r.name),
            format = esc(&r.format),
            mb = r.size as f64 / 1e6,
            sha = r.sha256.as_deref().map_or_else(|| "being computed".to_string(), |h| h[..16].to_string() + "…"),
        ));
    }
    let pick = rows
        .iter()
        .find(|r| r.format == "geoparquet-2.0" && r.name == "areas.parquet")
        .or_else(|| rows.iter().find(|r| r.format == "geoparquet-2.0"))
        .unwrap_or(&rows[0]);
    let region = esc(&pick.region);
    let where_bbox = if pick.format.starts_with("geoparquet") {
        "\nWHERE bbox.xmin <= MAXLON AND bbox.xmax >= MINLON\n  AND bbox.ymin <= MAXLAT AND bbox.ymax >= MINLAT"
    } else {
        ""
    };
    let duckdb = format!(
        "INSTALL httpfs; LOAD httpfs;\nINSTALL spatial; LOAD spatial;\nSELECT count(*)\nFROM 'ORIGIN{url}'{where_bbox};",
        url = esc(&pick.url),
    );
    format!(
        r#"
<h2>Files</h2>
<p>The region cuts as Parquet files, to download or to query where they are: the server
answers HTTP range requests, so DuckDB, pyarrow and GDAL (<code>/vsicurl/</code>) read only
the footer and the row groups a query needs. Files are sent as they are (Parquet pages are
compressed already), with <code>ETag</code> = the file's sha256.</p>
<div class="wrap"><table>
<tr><th>file</th><th>format</th><th>size</th><th>sha256</th></tr>
{table}</table></div>
<h3><code>GET /v1/files/{region}/</code></h3>
<p>The region's files as JSON: <code>name</code>, <code>format</code>, <code>size</code>,
<code>sha256</code>, <code>url</code>, <code>set</code>, <code>last_modified</code>.</p>
<pre>curl '<span class="origin"></span>/v1/files/{region}/'</pre>
<h3><code>GET</code>, <code>HEAD /v1/files/{{region}}/{{set}}/{{file}}</code></h3>
<p>One file: <code>Range: bytes=…</code> gives <code>206</code> (several ranges come as
<code>multipart/byteranges</code>), a range past the end <code>416</code>.</p>
<pre>curl -O '<span class="origin"></span>{url}'
curl -r 0-3 '<span class="origin"></span>{url}'   # PAR1</pre>
<h3>DuckDB</h3>
<pre data-ex-files="{duckdb}"></pre>
"#,
        url = esc(&pick.url),
        duckdb = duckdb.replace('"', "&quot;"),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn http_dates_are_imf_fixdate() {
        let t = |s: u64| http_date(UNIX_EPOCH + Duration::from_secs(s));
        assert_eq!(t(784_111_777), "Sun, 06 Nov 1994 08:49:37 GMT");
        assert_eq!(t(0), "Thu, 01 Jan 1970 00:00:00 GMT");
        assert_eq!(t(951_782_400), "Tue, 29 Feb 2000 00:00:00 GMT");
        assert_eq!(t(1_795_564_800), "Wed, 25 Nov 2026 00:00:00 GMT");
    }

    #[test]
    fn ranges_are_read_as_rfc_9110_says() {
        let p = |h: &str| parse_range(h, 1000);
        assert_eq!(p("bytes=0-99"), Ranges::Parts(vec![(0, 99)]));
        assert_eq!(p("bytes=900-"), Ranges::Parts(vec![(900, 999)]));
        assert_eq!(p("bytes=-8"), Ranges::Parts(vec![(992, 999)]));
        assert_eq!(p("bytes=-5000"), Ranges::Parts(vec![(0, 999)]));
        assert_eq!(p("bytes=990-5000"), Ranges::Parts(vec![(990, 999)]));
        assert_eq!(p("bytes=0-0, -1"), Ranges::Parts(vec![(0, 0), (999, 999)]));
        assert_eq!(p("bytes=1000-"), Ranges::Unsatisfiable);
        assert_eq!(p("bytes=5000-6000"), Ranges::Unsatisfiable);
        assert_eq!(p("bytes=-0"), Ranges::Unsatisfiable);
        assert_eq!(p("bytes=1000-, 0-1"), Ranges::Parts(vec![(0, 1)]));
        for ignored in [
            "",
            "items=0-1",
            "bytes=",
            "bytes=a-b",
            "bytes=5-1",
            "bytes=-",
            "bytes=1",
        ] {
            assert_eq!(p(ignored), Ranges::Whole, "{ignored:?}");
        }
        let many = format!("bytes={}", vec!["0-1"; MAX_RANGES + 1].join(","));
        assert_eq!(p(&many), Ranges::Whole);
        assert_eq!(parse_range("bytes=0-", 0), Ranges::Unsatisfiable);
    }

    #[test]
    fn a_flag_puts_the_parquet_files_of_a_directory_on_the_shelf() {
        let t = tempfile::tempdir().unwrap();
        std::fs::write(t.path().join("b.parquet"), b"PAR1....PAR1").unwrap();
        std::fs::write(t.path().join("a.parquet"), b"PAR1PAR1").unwrap();
        std::fs::write(t.path().join("notes.txt"), b"not served").unwrap();
        std::fs::create_dir(t.path().join("sub.parquet")).unwrap();
        let mut shelf = FileShelf::new();
        let set = shelf
            .add(&format!("testland={}", t.path().display()))
            .unwrap();
        assert_eq!(set.name, "parquet", "not GeoParquet: named by the format");
        let names: Vec<&str> = set.files.iter().map(|f| f.name.as_str()).collect();
        assert_eq!(names, ["a.parquet", "b.parquet"]);
        assert!(shelf.get("testland", "parquet", "a.parquet").is_some());
        for (r, s, f) in [
            ("testland", "parquet", "notes.txt"),
            ("testland", "parquet", "../a.parquet"),
            ("testland", "other", "a.parquet"),
            ("elsewhere", "parquet", "a.parquet"),
        ] {
            assert!(shelf.get(r, s, f).is_none(), "{r}/{s}/{f}");
        }
        let again = shelf.add(&format!("testland:raw={}", t.path().display()));
        assert_eq!(again.unwrap().name, "raw");
        let listing = shelf.listing(Some("testland")).unwrap();
        assert_eq!(listing.len(), 4);
        assert_eq!(listing[0].url, "/v1/files/testland/parquet/a.parquet");
        assert_eq!(listing[0].size, 8);
        assert_eq!(listing[0].sha256, None, "not hashed yet");
        assert_eq!(shelf.listing(Some("elsewhere")), None);
        let mut seen = 0;
        shelf.hash_all(|_, r| {
            assert!(r.is_ok());
            seen += 1;
        });
        assert_eq!(seen, 4);
        assert_eq!(
            shelf
                .get("testland", "parquet", "a.parquet")
                .unwrap()
                .sha256(),
            Some(sha256_hex(b"PAR1PAR1").as_str())
        );
    }

    fn sha256_hex(b: &[u8]) -> String {
        use sha2::Digest;
        sha2::Sha256::digest(b)
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect()
    }

    #[test]
    fn bad_flags_are_refused() {
        let t = tempfile::tempdir().unwrap();
        let empty = tempfile::tempdir().unwrap();
        std::fs::write(t.path().join("a.parquet"), b"x").unwrap();
        let d = t.path().display();
        let mut shelf = FileShelf::new();
        shelf.add(&format!("r={d}")).unwrap();
        for bad in [
            format!("{d}"),
            format!("r={d}"),
            format!("r/x={d}"),
            format!("r:..={d}"),
            format!("r:a b={d}"),
            format!("r={}", empty.path().display()),
            "r=/nonexistent/korp-map-files".to_string(),
        ] {
            assert!(shelf.add(&bad).is_err(), "{bad}");
        }
    }
}