Skip to main content

brep_app/help_local/
fixture.rs

1//! A local stand-in for the site's `web/help-bundle/`, for the help download's
2//! tests and the `help_fixture` command: a tiny bundle served on 127.0.0.1,
3//! never the real site. It can serve the archive halfway and HOLD there until
4//! released, so a script reads `downloading` and presses Cancel without a race.
5
6use std::io::{Read as _, Write as _};
7use std::net::{TcpListener, TcpStream};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::{Arc, Condvar, Mutex};
10use std::time::Duration;
11
12use sha2::{Digest, Sha256};
13
14use super::{BundleManifest, APP_VERSION, FORMAT};
15
16/// The version the `latest_only` bundle carries: newer than any real app.
17pub const LATEST_VERSION: &str = "99.0.0";
18
19/// What the server offers.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum Variant {
22    /// This app's version, and the same as the latest.
23    Ok,
24    /// This app's version, but the manifest's sha256 is not the archive's.
25    BadHash,
26    /// Only `brep-help-latest.json`, for version [`LATEST_VERSION`].
27    LatestOnly,
28    /// No manifest at all.
29    Missing,
30}
31
32impl Variant {
33    pub fn parse(s: &str) -> Result<Variant, String> {
34        match s {
35            "ok" => Ok(Variant::Ok),
36            "bad_hash" => Ok(Variant::BadHash),
37            "latest_only" => Ok(Variant::LatestOnly),
38            "missing" => Ok(Variant::Missing),
39            other => Err(format!("help fixture variant `{other}`: expected ok, bad_hash, latest_only or missing")),
40        }
41    }
42}
43
44/// A `.tar.gz` holding `index.html` and `features/page.html` for `version`.
45fn bundle(version: &str) -> Vec<u8> {
46    let mut tarball = Vec::new();
47    {
48        let mut b = tar::Builder::new(&mut tarball);
49        let index = format!("<!doctype html><title>BREP help</title><p>BREP help fixture {version}</p>");
50        // Large enough that a held download stops visibly halfway.
51        let page = format!("<!doctype html><p>{}</p>", "feature help ".repeat(40_000));
52        for (path, body) in [("./index.html", index.as_bytes()), ("./features/page.html", page.as_bytes())] {
53            let mut header = tar::Header::new_gnu();
54            header.set_size(body.len() as u64);
55            header.set_mode(0o644);
56            header.set_entry_type(tar::EntryType::Regular);
57            b.append_data(&mut header, path, body).expect("tar fixture");
58        }
59        b.finish().expect("tar fixture");
60    }
61    let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::none());
62    gz.write_all(&tarball).expect("gzip fixture");
63    gz.finish().expect("gzip fixture")
64}
65
66struct Shared {
67    variant: Variant,
68    archive: Vec<u8>,
69    version: String,
70    hold: Mutex<bool>,
71    released: Condvar,
72    stop: AtomicBool,
73    requests: Mutex<Vec<String>>,
74}
75
76impl Shared {
77    fn manifest(&self) -> String {
78        let mut sha: String = Sha256::digest(&self.archive).iter().map(|b| format!("{b:02x}")).collect();
79        if self.variant == Variant::BadHash {
80            sha = sha.chars().rev().collect();
81        }
82        serde_json::to_string(&BundleManifest {
83            format: FORMAT.into(),
84            version: self.version.clone(),
85            file: format!("brep-help-{}.tar.gz", self.version),
86            sha256: sha,
87            bytes: self.archive.len() as u64,
88        })
89        .unwrap_or_default()
90    }
91
92    fn answer(&self, path: &str) -> Option<(&'static str, Vec<u8>)> {
93        let own = format!("/brep-help-{APP_VERSION}.json");
94        let archive = format!("/brep-help-{}.tar.gz", self.version);
95        let has_own = matches!(self.variant, Variant::Ok | Variant::BadHash);
96        let has_latest = self.variant != Variant::Missing;
97        if path == own && has_own || path == "/brep-help-latest.json" && has_latest {
98            Some(("application/json", self.manifest().into_bytes()))
99        } else if path == archive && has_latest {
100            Some(("application/gzip", self.archive.clone()))
101        } else {
102            None
103        }
104    }
105}
106
107/// The running server. Dropped (or [`Self::stop`]ped) it stops listening.
108pub struct FixtureServer {
109    pub url: String,
110    port: u16,
111    shared: Arc<Shared>,
112    thread: Option<std::thread::JoinHandle<()>>,
113}
114
115impl FixtureServer {
116    pub fn start(variant: Variant) -> Result<FixtureServer, String> {
117        Self::listen(variant, 0)
118    }
119
120    fn listen(variant: Variant, port: u16) -> Result<FixtureServer, String> {
121        let listener = TcpListener::bind(("127.0.0.1", port)).map_err(|e| format!("help fixture: {e}"))?;
122        let port = listener.local_addr().map_err(|e| e.to_string())?.port();
123        listener.set_nonblocking(true).map_err(|e| e.to_string())?;
124        let version = if variant == Variant::LatestOnly { LATEST_VERSION } else { APP_VERSION };
125        let shared = Arc::new(Shared {
126            variant,
127            archive: bundle(version),
128            version: version.to_string(),
129            hold: Mutex::new(false),
130            released: Condvar::new(),
131            stop: AtomicBool::new(false),
132            requests: Mutex::new(Vec::new()),
133        });
134        let s = shared.clone();
135        let thread = std::thread::Builder::new()
136            .name("brep-help-fixture".into())
137            .spawn(move || {
138                while !s.stop.load(Ordering::Relaxed) {
139                    match listener.accept() {
140                        Ok((stream, _)) => {
141                            let s = s.clone();
142                            let _ = std::thread::Builder::new().name("brep-help-fixture-conn".into()).spawn(move || serve(&s, stream));
143                        }
144                        Err(_) => std::thread::sleep(Duration::from_millis(15)),
145                    }
146                }
147            })
148            .map_err(|e| e.to_string())?;
149        Ok(FixtureServer { url: format!("http://127.0.0.1:{port}"), port, shared, thread: Some(thread) })
150    }
151
152    /// The same port again, offering `variant` (after a stop, or to switch).
153    pub fn restart(mut self, variant: Variant) -> Result<FixtureServer, String> {
154        let port = self.port;
155        self.stop();
156        Self::listen(variant, port)
157    }
158
159    /// Hold the archive halfway (`true`) or let it finish.
160    pub fn set_hold(&self, hold: bool) {
161        if let Ok(mut h) = self.shared.hold.lock() {
162            *h = hold;
163        }
164        self.shared.released.notify_all();
165    }
166
167    /// The paths asked for so far, in order.
168    pub fn requests(&self) -> Vec<String> {
169        self.shared.requests.lock().map(|r| r.clone()).unwrap_or_default()
170    }
171
172    pub fn stop(&mut self) {
173        self.shared.stop.store(true, Ordering::Relaxed);
174        self.set_hold(false);
175        if let Some(t) = self.thread.take() {
176            let _ = t.join();
177        }
178    }
179}
180
181impl Drop for FixtureServer {
182    fn drop(&mut self) {
183        self.stop();
184    }
185}
186
187fn serve(s: &Shared, mut stream: TcpStream) {
188    let _ = stream.set_nonblocking(false);
189    let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
190    let mut head = Vec::new();
191    let mut byte = [0u8; 1];
192    while !head.ends_with(b"\r\n\r\n") && head.len() < 16 * 1024 {
193        match stream.read(&mut byte) {
194            Ok(1) => head.push(byte[0]),
195            _ => return,
196        }
197    }
198    let head = String::from_utf8_lossy(&head);
199    let path = head.split_whitespace().nth(1).unwrap_or("/").to_string();
200    if let Ok(mut r) = s.requests.lock() {
201        r.push(path.clone());
202    }
203    let Some((kind, body)) = s.answer(&path) else {
204        let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\nConnection: close\r\n\r\nnot found");
205        return;
206    };
207    let header = format!("HTTP/1.1 200 OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
208    if stream.write_all(header.as_bytes()).is_err() {
209        return;
210    }
211    let half = if kind == "application/gzip" { body.len() / 2 } else { body.len() };
212    if stream.write_all(&body[..half]).is_err() || stream.flush().is_err() {
213        return;
214    }
215    if half < body.len() {
216        if let Ok(mut held) = s.hold.lock() {
217            while *held && !s.stop.load(Ordering::Relaxed) {
218                held = match s.released.wait_timeout(held, Duration::from_millis(100)) {
219                    Ok((h, _)) => h,
220                    Err(_) => return,
221                };
222            }
223        }
224        if s.stop.load(Ordering::Relaxed) {
225            return;
226        }
227        let _ = stream.write_all(&body[half..]);
228    }
229}