BREP_app 0.35.0

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
//! A local stand-in for the site's `web/help-bundle/`, for the help download's
//! tests and the `help_fixture` command: a tiny bundle served on 127.0.0.1,
//! never the real site. It can serve the archive halfway and HOLD there until
//! released, so a script reads `downloading` and presses Cancel without a race.

use std::io::{Read as _, Write as _};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;

use sha2::{Digest, Sha256};

use super::{BundleManifest, APP_VERSION, FORMAT};

/// The version the `latest_only` bundle carries: newer than any real app.
pub const LATEST_VERSION: &str = "99.0.0";

/// What the server offers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Variant {
    /// This app's version, and the same as the latest.
    Ok,
    /// This app's version, but the manifest's sha256 is not the archive's.
    BadHash,
    /// Only `brep-help-latest.json`, for version [`LATEST_VERSION`].
    LatestOnly,
    /// No manifest at all.
    Missing,
}

impl Variant {
    pub fn parse(s: &str) -> Result<Variant, String> {
        match s {
            "ok" => Ok(Variant::Ok),
            "bad_hash" => Ok(Variant::BadHash),
            "latest_only" => Ok(Variant::LatestOnly),
            "missing" => Ok(Variant::Missing),
            other => Err(format!("help fixture variant `{other}`: expected ok, bad_hash, latest_only or missing")),
        }
    }
}

/// A `.tar.gz` holding `index.html` and `features/page.html` for `version`.
fn bundle(version: &str) -> Vec<u8> {
    let mut tarball = Vec::new();
    {
        let mut b = tar::Builder::new(&mut tarball);
        let index = format!("<!doctype html><title>BREP help</title><p>BREP help fixture {version}</p>");
        // Large enough that a held download stops visibly halfway.
        let page = format!("<!doctype html><p>{}</p>", "feature help ".repeat(40_000));
        for (path, body) in [("./index.html", index.as_bytes()), ("./features/page.html", page.as_bytes())] {
            let mut header = tar::Header::new_gnu();
            header.set_size(body.len() as u64);
            header.set_mode(0o644);
            header.set_entry_type(tar::EntryType::Regular);
            b.append_data(&mut header, path, body).expect("tar fixture");
        }
        b.finish().expect("tar fixture");
    }
    let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::none());
    gz.write_all(&tarball).expect("gzip fixture");
    gz.finish().expect("gzip fixture")
}

struct Shared {
    variant: Variant,
    archive: Vec<u8>,
    version: String,
    hold: Mutex<bool>,
    released: Condvar,
    stop: AtomicBool,
    requests: Mutex<Vec<String>>,
}

impl Shared {
    fn manifest(&self) -> String {
        let mut sha: String = Sha256::digest(&self.archive).iter().map(|b| format!("{b:02x}")).collect();
        if self.variant == Variant::BadHash {
            sha = sha.chars().rev().collect();
        }
        serde_json::to_string(&BundleManifest {
            format: FORMAT.into(),
            version: self.version.clone(),
            file: format!("brep-help-{}.tar.gz", self.version),
            sha256: sha,
            bytes: self.archive.len() as u64,
        })
        .unwrap_or_default()
    }

    fn answer(&self, path: &str) -> Option<(&'static str, Vec<u8>)> {
        let own = format!("/brep-help-{APP_VERSION}.json");
        let archive = format!("/brep-help-{}.tar.gz", self.version);
        let has_own = matches!(self.variant, Variant::Ok | Variant::BadHash);
        let has_latest = self.variant != Variant::Missing;
        if path == own && has_own || path == "/brep-help-latest.json" && has_latest {
            Some(("application/json", self.manifest().into_bytes()))
        } else if path == archive && has_latest {
            Some(("application/gzip", self.archive.clone()))
        } else {
            None
        }
    }
}

/// The running server. Dropped (or [`Self::stop`]ped) it stops listening.
pub struct FixtureServer {
    pub url: String,
    port: u16,
    shared: Arc<Shared>,
    thread: Option<std::thread::JoinHandle<()>>,
}

impl FixtureServer {
    pub fn start(variant: Variant) -> Result<FixtureServer, String> {
        Self::listen(variant, 0)
    }

    fn listen(variant: Variant, port: u16) -> Result<FixtureServer, String> {
        let listener = TcpListener::bind(("127.0.0.1", port)).map_err(|e| format!("help fixture: {e}"))?;
        let port = listener.local_addr().map_err(|e| e.to_string())?.port();
        listener.set_nonblocking(true).map_err(|e| e.to_string())?;
        let version = if variant == Variant::LatestOnly { LATEST_VERSION } else { APP_VERSION };
        let shared = Arc::new(Shared {
            variant,
            archive: bundle(version),
            version: version.to_string(),
            hold: Mutex::new(false),
            released: Condvar::new(),
            stop: AtomicBool::new(false),
            requests: Mutex::new(Vec::new()),
        });
        let s = shared.clone();
        let thread = std::thread::Builder::new()
            .name("brep-help-fixture".into())
            .spawn(move || {
                while !s.stop.load(Ordering::Relaxed) {
                    match listener.accept() {
                        Ok((stream, _)) => {
                            let s = s.clone();
                            let _ = std::thread::Builder::new().name("brep-help-fixture-conn".into()).spawn(move || serve(&s, stream));
                        }
                        Err(_) => std::thread::sleep(Duration::from_millis(15)),
                    }
                }
            })
            .map_err(|e| e.to_string())?;
        Ok(FixtureServer { url: format!("http://127.0.0.1:{port}"), port, shared, thread: Some(thread) })
    }

    /// The same port again, offering `variant` (after a stop, or to switch).
    pub fn restart(mut self, variant: Variant) -> Result<FixtureServer, String> {
        let port = self.port;
        self.stop();
        Self::listen(variant, port)
    }

    /// Hold the archive halfway (`true`) or let it finish.
    pub fn set_hold(&self, hold: bool) {
        if let Ok(mut h) = self.shared.hold.lock() {
            *h = hold;
        }
        self.shared.released.notify_all();
    }

    /// The paths asked for so far, in order.
    pub fn requests(&self) -> Vec<String> {
        self.shared.requests.lock().map(|r| r.clone()).unwrap_or_default()
    }

    pub fn stop(&mut self) {
        self.shared.stop.store(true, Ordering::Relaxed);
        self.set_hold(false);
        if let Some(t) = self.thread.take() {
            let _ = t.join();
        }
    }
}

impl Drop for FixtureServer {
    fn drop(&mut self) {
        self.stop();
    }
}

fn serve(s: &Shared, mut stream: TcpStream) {
    let _ = stream.set_nonblocking(false);
    let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
    let mut head = Vec::new();
    let mut byte = [0u8; 1];
    while !head.ends_with(b"\r\n\r\n") && head.len() < 16 * 1024 {
        match stream.read(&mut byte) {
            Ok(1) => head.push(byte[0]),
            _ => return,
        }
    }
    let head = String::from_utf8_lossy(&head);
    let path = head.split_whitespace().nth(1).unwrap_or("/").to_string();
    if let Ok(mut r) = s.requests.lock() {
        r.push(path.clone());
    }
    let Some((kind, body)) = s.answer(&path) else {
        let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\nConnection: close\r\n\r\nnot found");
        return;
    };
    let header = format!("HTTP/1.1 200 OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
    if stream.write_all(header.as_bytes()).is_err() {
        return;
    }
    let half = if kind == "application/gzip" { body.len() / 2 } else { body.len() };
    if stream.write_all(&body[..half]).is_err() || stream.flush().is_err() {
        return;
    }
    if half < body.len() {
        if let Ok(mut held) = s.hold.lock() {
            while *held && !s.stop.load(Ordering::Relaxed) {
                held = match s.released.wait_timeout(held, Duration::from_millis(100)) {
                    Ok((h, _)) => h,
                    Err(_) => return,
                };
            }
        }
        if s.stop.load(Ordering::Relaxed) {
            return;
        }
        let _ = stream.write_all(&body[half..]);
    }
}