// SPDX-License-Identifier: CPAL-1.0 // Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution // License 1.0: see LICENSE (its Exhibit A is this file's notice). //! `ianitor-pair`: Ianitor (edge, in this process) and Caddy side by side on 127.0.0.1, //! serving the same routes compiled by core, for the conformance and load scripts //! (scripts/conformance.sh, scripts/bench.sh; ROADMAP §5 layers 2 and 5). //! //! One host, `localhost` (a Domi-style certificate from a throwaway test CA), proxied to a //! small upstream that answers `200 ok` and records nothing; it runs as a child process //! (`ianitor-pair --upstream`), so this process's memory is edge's (plus a small runtime). Two Caddys run: //! one as Go starts it (every core) and one with `GOMAXPROCS=2`, since edge runs Pingora with //! two worker threads (crates/edge/src/lib.rs). Prints one JSON line with the addresses and the //! CA file, then serves until SIGTERM or SIGINT. //! //! `ianitor-pair [--caddy ]` (default: `caddy` on PATH or `$IANITOR_CADDY_BIN`). #[cfg(not(unix))] fn main() { eprintln!("ianitor-pair needs Linux (the Pingora runner and Caddy); run it in WSL2"); std::process::exit(2); } #[cfg(unix)] fn main() { #[allow(clippy::expect_used)] let rt = tokio::runtime::Runtime::new().expect("a tokio runtime"); rt.block_on(unix::main()); } #[cfg(unix)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod unix { use std::convert::Infallible; use std::net::SocketAddr; use http_body_util::Full; use hyper::server::conn::http1; use hyper::service::service_fn; use hyper_util::rt::TokioIo; use ianitor_core::compile::{self, CompileOptions}; use ianitor_core::{SourceFile, load}; use ianitor_diff::{Target, start_caddy_in, start_edge_in}; use ianitor_testkit::proc::{ChildGuard, TempDir, find_binary, free_port, local}; use ianitor_testkit::tls::TestCa; use serde_json::json; /// `--upstream`: serve `200 ok` on a free loopback port, print it, run until killed. async fn serve_upstream() { let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); println!("{}", l.local_addr().unwrap()); loop { let Ok((s, _)) = l.accept().await else { continue; }; tokio::spawn(async move { let svc = service_fn(|_req| async { Ok::<_, Infallible>(hyper::Response::new(Full::new(bytes::Bytes::from_static( b"ok\n", )))) }); let _ = http1::Builder::new() .serve_connection(TokioIo::new(s), svc) .await; }); } } /// The upstream as a child process; its address. fn upstream() -> (ChildGuard, SocketAddr) { use std::io::BufRead; let mut child = std::process::Command::new(std::env::current_exe().unwrap()) .arg("--upstream") .stdout(std::process::Stdio::piped()) .spawn() .unwrap(); let out = child.stdout.take().unwrap(); let mut line = String::new(); std::io::BufReader::new(out).read_line(&mut line).unwrap(); (ChildGuard(child), line.trim().parse().unwrap()) } fn options(dir: &TempDir, engine: &str) -> CompileOptions { CompileOptions { http_listen: local(free_port()), https_listen: local(free_port()), cert_dir: dir.str("certs"), state_dir: dir.str(&format!("state-{engine}")), access_log: dir.str(&format!("logs/{engine}-access.log")), caddy_credentials_dir: dir.str("creds"), caddy_admin: None, caddy_admin_socket: None, trusted_proxies: Vec::new(), proxy_socket: None, } } /// `caddy version`, or, for a `go install`ed Caddy that says "unknown", its module version /// from the binary's build info (`go version -m`). fn caddy_version(caddy: &std::path::Path) -> String { let out = |cmd: &mut std::process::Command| { cmd.output() .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()) .unwrap_or_default() }; let v = out(std::process::Command::new(caddy).arg("version")); if !v.is_empty() && v != "unknown" { return v; } let info = out(std::process::Command::new("go") .args(["version", "-m"]) .arg(caddy)); info.lines() .map(|l| l.split_whitespace().collect::>()) .find(|f| f.len() >= 3 && f[0] == "mod" && f[1] == "github.com/caddyserver/caddy/v2") .map(|f| { format!( "{} (go install; {})", f[2], info.lines().next().unwrap_or("").trim() ) }) .unwrap_or(v) } fn addrs(t: &Target) -> serde_json::Value { json!({ "http": t.http.to_string(), "https": t.https.to_string() }) } pub async fn main() { let args: Vec = std::env::args().collect(); if args.iter().any(|a| a == "--upstream") { serve_upstream().await; return; } let caddy = args .iter() .position(|a| a == "--caddy") .and_then(|i| args.get(i + 1)) .map(std::path::PathBuf::from) .or_else(|| find_binary("caddy")) .unwrap_or_else(|| panic!("no caddy: pass --caddy or put it on PATH")); let (upstream_child, up) = upstream(); let dir = TempDir::new("pair"); for d in [ "certs", "creds", "logs", "state-edge", "state-caddy", "state-caddy2", "xdg", ] { std::fs::create_dir_all(dir.join(d)).unwrap(); } let ca = TestCa::new("Ianitor Pair Test CA"); let leaf = ca.issue(&["localhost"]); std::fs::write(dir.join("certs/localhost.crt"), leaf.cert_pem).unwrap(); std::fs::write(dir.join("certs/localhost.key"), leaf.key_pem).unwrap(); std::fs::write(dir.join("ca.pem"), &ca.cert_pem).unwrap(); let host = format!("hostname = \"localhost\"\ntls = \"domi\"\nupstreams = [\"http://{up}\"]\n"); let model = load( &SourceFile { name: "ianitor.toml", contents: "", }, &[SourceFile { name: "hosts/localhost.toml", contents: &host, }], ) .expect("valid routes"); let edge_cfg = compile::edge(&model, &options(&dir, "edge")).unwrap(); let caddy_cfg = compile::caddy(&model, &options(&dir, "caddy")).unwrap(); let caddy2_cfg = compile::caddy(&model, &options(&dir, "caddy2")).unwrap(); let ianitor = start_edge_in(dir.path(), "ianitor", &edge_cfg); let caddy_all = start_caddy_in(dir.path(), "caddy", &caddy, &caddy_cfg, &[]); let caddy_two = start_caddy_in( dir.path(), "caddy2", &caddy, &caddy2_cfg, &[("GOMAXPROCS", "2")], ); let caddy_version = caddy_version(&caddy); println!( "{}", json!({ "host": "localhost", "ca": dir.join("ca.pem"), "dir": dir.path(), "upstream": up.to_string(), "ianitor": addrs(&ianitor), "caddy": addrs(&caddy_all), "caddy_gomaxprocs2": addrs(&caddy_two), "edge_threads": 2, "build": if cfg!(debug_assertions) { "debug" } else { "release" }, "caddy_version": caddy_version, }) ); use tokio::signal::unix::{SignalKind, signal}; let mut term = signal(SignalKind::terminate()).unwrap(); tokio::select! { _ = tokio::signal::ctrl_c() => {} _ = term.recv() => {} } drop((ianitor, caddy_all, caddy_two, upstream_child)); } }