garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/web.rs

raw

//! The hub's web page (`web/`, a Mithril app): the workspace's state, its network,
//! its history, and the controls a caller key allows. Built by `bun run build`
//! into `web/dist/` and carried inside the binary, so the hub serves it with
//! nothing beside it to install or fall out of step.
//!
//! The page reads the same open `/v1/…` API everything else does, and sends a
//! change with the caller key a person pastes into it; it has no access of its
//! own.

use sha2::{Digest, Sha256};
use std::sync::OnceLock;

/// A file of the page: its content type, its bytes, the same gzipped when the
/// build made them so, and a tag that changes with the bytes.
pub struct Asset {
    pub ctype: &'static str,
    pub body: &'static [u8],
    pub gzip: Option<&'static [u8]>,
    pub etag: &'static str,
}

/// The file for a path. A place of the page (`/sessions/s3`, `/setup/<token>`: no
/// file's name, no dot in its last part) is the page itself, which reads the
/// place from its address; a file it does not carry is none.
pub fn asset(path: &str) -> Option<&'static Asset> {
    let rest = path.strip_prefix('/')?;
    let name = match rest {
        "" | "index.html" => "index.html",
        p if FILES.iter().any(|f| f.0 == p) => p,
        p if !p.starts_with("v1/") && !p.rsplit('/').next().unwrap_or("").contains('.') => "index.html",
        _ => return None,
    };
    static ASSETS: OnceLock<Vec<(&'static str, Asset)>> = OnceLock::new();
    let all = ASSETS.get_or_init(|| {
        FILES
            .iter()
            .map(|&(n, ctype, body, gzip)| {
                let hash = data_encoding::HEXLOWER.encode(&Sha256::digest(body)[..8]);
                (n, Asset { ctype, body, gzip, etag: Box::leak(format!("\"{hash}\"").into_boxed_str()) })
            })
            .collect()
    });
    all.iter().find(|(n, _)| *n == name).map(|(_, a)| a)
}

/// Which build of the page this hub serves: a tag that changes with any of its
/// files. Sent with each snapshot (ws.rs), so a page left open notices a deploy
/// and loads the new one rather than running the old code for days.
pub fn build() -> &'static str {
    static BUILD: OnceLock<String> = OnceLock::new();
    BUILD.get_or_init(|| {
        let mut h = Sha256::new();
        for (_, _, body, _) in FILES {
            h.update(body);
        }
        data_encoding::HEXLOWER.encode(&h.finalize()[..8])
    })
}

#[cfg(midas_web)]
const FILES: &[(&str, &str, &[u8], Option<&[u8]>)] = &[
    ("index.html", "text/html; charset=utf-8", include_bytes!("../web/dist/index.html"), None),
    ("app.js", "text/javascript; charset=utf-8", include_bytes!("../web/dist/app.js"), Some(include_bytes!("../web/dist/app.js.gz"))),
    ("app.css", "text/css; charset=utf-8", include_bytes!("../web/dist/app.css"), Some(include_bytes!("../web/dist/app.css.gz"))),
    // At the root, so its scope is the whole page: it shows the notifications (push.rs).
    ("sw.js", "text/javascript; charset=utf-8", include_bytes!("../web/dist/sw.js"), None),
    ("manifest.json", "application/manifest+json", include_bytes!("../web/dist/manifest.json"), None),
    // The logo: the tab's icon and the head's; the PNGs for a phone's home screen, which takes no SVG.
    ("icon.svg", "image/svg+xml", include_bytes!("../web/dist/icon.svg"), None),
    ("icon-192.png", "image/png", include_bytes!("../web/dist/icon-192.png"), None),
    ("icon-512.png", "image/png", include_bytes!("../web/dist/icon-512.png"), None),
];

#[cfg(not(midas_web))]
const FILES: &[(&str, &str, &[u8], Option<&[u8]>)] = &[(
    "index.html",
    "text/html; charset=utf-8",
    b"<!doctype html><meta charset=utf-8><title>midas</title>\
      <p>This midas was built without its web page: <code>cd web &amp;&amp; bun install &amp;&amp; bun run build</code>, \
      then build midas again (<code>./deploy.sh</code> does both).",
    None,
)];

#[cfg(test)]
mod tests {
    use super::asset;

    #[test]
    fn a_place_of_the_page_is_the_page() {
        let page = asset("/").unwrap().etag;
        for p in ["/index.html", "/sessions", "/sessions/s3", "/activity/events", "/setup/0a1b2c"] {
            assert_eq!(asset(p).map(|a| a.etag), Some(page), "{p}");
        }
        for p in ["/favicon.ico", "/sessions/s3/x.png", "/v1/nothing", "nothing"] {
            assert!(asset(p).is_none(), "{p}");
        }
    }

    #[cfg(midas_web)]
    #[test]
    fn the_logo_is_served_with_its_type() {
        assert_eq!(asset("/icon.svg").map(|a| a.ctype), Some("image/svg+xml"));
        assert_eq!(asset("/icon-192.png").map(|a| a.ctype), Some("image/png"));
    }
}