diff --git a/README.md b/README.md index 3771fb0..4ccfdfb 100644 --- a/README.md +++ b/README.md @@ -121,3 +121,9 @@ A release is a push to `main` here, then `nix flake update visa` in cnx-network-clan and a deploy of cnx01. The fleet's VM test `checks.visa` signs in through a fake provider, adds a person and checks the audit log on the real PostgreSQL module. + +Which commit runs: every page's footer names it, with a link to it, and +https://visa.buildfor.life/version answers with the full hash, without a +login, so `curl https://visa.buildfor.life/version` tells whether a release +is live. A Nix build takes the commit from the flake's source; a build in a +checkout asks git. diff --git a/build.rs b/build.rs index 6621bf8..9e4c7ac 100644 --- a/build.rs +++ b/build.rs @@ -1,7 +1,8 @@ //! Lists every file of templates/ and static/ for `src/embedded.rs`: one //! `(name, include_bytes!(..))` pair per file, sorted by name, so the binary //! carries its pages and needs no files next to it. Also a short hash of the -//! static files for cache busting (`/static/app.css?v=`). +//! static files for cache busting (`/static/app.css?v=`), and the +//! commit the binary is built from (`COMMIT`). use std::fmt::Write as _; use std::path::{Path, PathBuf}; @@ -39,10 +40,50 @@ fn main() { hash >> 16 ) .unwrap(); + // The commit, for the footer and /version. A Nix build has no .git, so + // the flake passes its source's revision in VISA_COMMIT; a build in a + // checkout asks git; otherwise it stays empty. + println!("cargo:rerun-if-env-changed=VISA_COMMIT"); + let commit = std::env::var("VISA_COMMIT") + .ok() + .filter(|c| !c.is_empty()) + .or_else(|| git_head(&root)) + .unwrap_or_default(); + writeln!(out, "pub const COMMIT: &str = {commit:?};").unwrap(); let dest = Path::new(&std::env::var_os("OUT_DIR").unwrap()).join("embedded.rs"); std::fs::write(dest, out).unwrap(); } +/// HEAD's commit in a git checkout. The script runs again when HEAD or the +/// branch it names moves. +fn git_head(root: &Path) -> Option { + let git = |args: &[&str]| { + std::process::Command::new("git") + .args(args) + .current_dir(root) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) + }; + let head = git(&["rev-parse", "HEAD"])?; + let dir = PathBuf::from(git(&["rev-parse", "--absolute-git-dir"])?); + let common = PathBuf::from(git(&[ + "rev-parse", + "--path-format=absolute", + "--git-common-dir", + ])?); + let mut watch = vec![dir.join("HEAD"), common.join("packed-refs")]; + if let Some(branch) = git(&["symbolic-ref", "-q", "HEAD"]) { + watch.push(common.join(branch)); + } + // a path that does not exist would make cargo run the script every time + for p in watch.iter().filter(|p| p.exists()) { + println!("cargo:rerun-if-changed={}", p.display()); + } + Some(head) +} + fn walk(base: &Path, dir: &Path, out: &mut Vec<(String, String)>) { let Ok(entries) = std::fs::read_dir(dir) else { return; diff --git a/docs/PLAN.md b/docs/PLAN.md index f907371..9238268 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -312,6 +312,12 @@ one `Kind`. taken as 2025. - [x] 5.6 Audit: opening or downloading a form is logged as `form` with the codes of the forms, never their values. +- [x] 5.7 The commit that runs, asked for on November 18, 2026: the footer + of every page names it with a link to it, and `/version` answers with + the full hash without a login. The flake passes its source's revision + to build.rs as `VISA_COMMIT`, set on the package alone so that the + dependencies' build stays the same; a build in a checkout asks git. + Live with the release after `a2cedcd`. ## Open questions diff --git a/flake.nix b/flake.nix index e324a3a..3379335 100644 --- a/flake.nix +++ b/flake.nix @@ -58,6 +58,10 @@ // { inherit cargoArtifacts; cargoExtraArgs = "--locked --bin visa"; + # The commit for the footer and /version (build.rs). Set here only, + # not in `common`, so the dependencies' build stays the same from + # commit to commit. + VISA_COMMIT = self.rev or self.dirtyRev or ""; meta = { description = "Immigration records, deadlines and extension packs for foreigners in Thailand"; homepage = "https://git.b4l.co.th/B4L/visa"; diff --git a/src/embedded.rs b/src/embedded.rs index 0b1ac8e..c30e4a7 100644 --- a/src/embedded.rs +++ b/src/embedded.rs @@ -1,7 +1,29 @@ -//! Templates and static files compiled into the binary (build.rs). +//! Templates and static files compiled into the binary (build.rs), and the +//! commit the binary is built from. include!(concat!(env!("OUT_DIR"), "/embedded.rs")); +/// Where the commits are. +const COMMITS: &str = "https://git.b4l.co.th/B4L/visa/commit/"; + +/// A commit as people read it: its first seven digits, with "-dirty" when the +/// binary was built from a tree with changes. Empty when there is none. +pub fn short(commit: &str) -> String { + match commit.get(..7) { + Some(head) if commit.ends_with("-dirty") => format!("{head}-dirty"), + Some(head) => head.to_string(), + None => String::new(), + } +} + +/// The commit's page on the forge; a dirty build links its base commit. +pub fn url(commit: &str) -> Option { + let full = commit.get(..40)?; + full.bytes() + .all(|b| b.is_ascii_hexdigit()) + .then(|| format!("{COMMITS}{full}")) +} + pub fn static_file(path: &str) -> Option<&'static [u8]> { STATIC .iter() @@ -39,3 +61,21 @@ mod tests { assert_eq!(STATIC_HASH.len(), 12); } } + +#[cfg(test)] +mod commit_tests { + use super::*; + + #[test] + fn the_commit_as_people_read_it() { + let c = "a2cedcdd7e9d05bd63ca079e6f701a9e3954093f"; + let page = format!("{COMMITS}{c}"); + assert_eq!(short(c), "a2cedcd"); + assert_eq!(url(c), Some(page.clone())); + let dirty = format!("{c}-dirty"); + assert_eq!(short(&dirty), "a2cedcd-dirty"); + assert_eq!(url(&dirty), Some(page)); + assert_eq!((short(""), url("")), (String::new(), None)); + assert_eq!(url("not a commit, but forty characters long!"), None); + } +} diff --git a/src/web/mod.rs b/src/web/mod.rs index d309355..97fb7e4 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -311,6 +311,7 @@ pub fn router(st: Arc) -> Router { .route("/logout", post(auth::logout)) .route("/signed-out", get(auth::signed_out)) .route("/healthz", get(healthz)) + .route("/version", get(version)) .route("/static/{*path}", get(static_file)) // asked for by pages without their own icon: an image or a PDF .route( @@ -328,7 +329,7 @@ pub fn router(st: Arc) -> Router { fn is_public(path: &str) -> bool { matches!( path, - "/healthz" | "/login" | "/auth/callback" | "/signed-out" | "/favicon.ico" + "/healthz" | "/version" | "/login" | "/auth/callback" | "/signed-out" | "/favicon.ico" ) || path.starts_with("/static/") } @@ -569,6 +570,8 @@ pub fn page( csrf => &user.csrf, v => embedded::STATIC_HASH, version => VERSION, + commit => embedded::short(embedded::COMMIT), + commit_url => embedded::url(embedded::COMMIT), ..ctx }; render(st, name, full, status) @@ -623,6 +626,23 @@ async fn healthz(State(st): State>) -> Response { } } +/// The commit that runs, in full, for scripts and the fleet's checks; open +/// without a session, like the health check. +async fn version() -> Response { + let commit = match embedded::COMMIT { + "" => "unknown", + c => c, + }; + ( + [ + (header::CONTENT_TYPE, "text/plain; charset=utf-8"), + (header::CACHE_CONTROL, "no-store"), + ], + format!("{commit}\n"), + ) + .into_response() +} + async fn static_file(Path(path): Path) -> Response { match embedded::static_file(&path) { Some(bytes) => ( diff --git a/templates/base.html b/templates/base.html index 6bb3a65..bd1ee08 100644 --- a/templates/base.html +++ b/templates/base.html @@ -41,7 +41,7 @@
{% block main %}{% endblock %} -
visa.buildfor.life {{ version }}. Every view and change of a person's record is written to the Activity log. Dates are in Chiang Mai time.
+
visa.buildfor.life {{ version }}{% if commit %}, commit {% if commit_url %}{{ commit }}{% else %}{{ commit }}{% endif %}{% endif %}. Every view and change of a person's record is written to the Activity log. Dates are in Chiang Mai time.
diff --git a/tests/auth.rs b/tests/auth.rs index 6a0e874..7172ae2 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -34,6 +34,7 @@ async fn the_gate_sends_people_to_the_login(pool: PgPool) { assert_eq!(r.headers["hx-redirect"], "/login?next=/people"); // open without a session assert_eq!(app.get("/healthz").await.status, StatusCode::OK); + assert_eq!(app.get("/version").await.status, StatusCode::OK); assert_eq!(app.get("/static/app.css").await.status, StatusCode::OK); assert_eq!(app.get("/signed-out").await.status, StatusCode::OK); // the provider has not answered yet diff --git a/tests/pages.rs b/tests/pages.rs index b5848b6..8575fea 100644 --- a/tests/pages.rs +++ b/tests/pages.rs @@ -216,6 +216,24 @@ async fn open_paths_headers_and_not_found(pool: PgPool) { let app = local(pool); let r = app.get("/healthz").await; assert_eq!((r.status, r.body.as_str()), (StatusCode::OK, "ok")); + // the commit that runs, in full; the footer shows its first digits + let r = app.get("/version").await; + let commit = visa::embedded::COMMIT; + let want = if commit.is_empty() { "unknown" } else { commit }; + assert_eq!( + (r.status, r.body.as_str()), + (StatusCode::OK, format!("{want}\n").as_str()) + ); + assert_eq!(r.headers["cache-control"], "no-store"); + let short = visa::embedded::short(commit); + if !short.is_empty() { + let t = app.get("/people").await.text(); + assert!( + t.contains(", commit {short}. Every view")), "{t}"); + } let css = app.get("/static/app.css").await; assert_eq!(css.status, StatusCode::OK); assert_eq!(css.headers["content-type"], "text/css; charset=utf-8");