forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·10.2 MiB·3cdd794·Tahinli·13 minutes ago·331 commits
| 1 | use std::fs; |
| 2 | use std::net::TcpStream; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::process::{Child, Command, ExitStatus, Output, Stdio}; |
| 5 | use std::sync::OnceLock; |
| 6 | use std::time::{Duration, Instant}; |
| 7 | |
| 8 | mod http; |
| 9 | |
| 10 | pub use http::{Http, Resp, cookie_named, csrf_for, login, open_stream, with_cookie}; |
| 11 | |
| 12 | pub fn bin() -> &'static str { |
| 13 | static BIN: OnceLock<String> = OnceLock::new(); |
| 14 | BIN.get_or_init(|| match std::env::var("FORGE_BIN") { |
| 15 | Ok(path) if !path.is_empty() => path, |
| 16 | _ => build_forge(), |
| 17 | }) |
| 18 | .as_str() |
| 19 | } |
| 20 | |
| 21 | fn build_forge() -> String { |
| 22 | let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_owned()); |
| 23 | let output = Command::new(&cargo) |
| 24 | .args([ |
| 25 | "build", |
| 26 | "-p", |
| 27 | "forge-web", |
| 28 | "--bin", |
| 29 | "forge", |
| 30 | "--message-format=json-render-diagnostics", |
| 31 | ]) |
| 32 | .current_dir(env!("CARGO_MANIFEST_DIR")) |
| 33 | .stderr(Stdio::inherit()) |
| 34 | .output() |
| 35 | .unwrap_or_else(|e| panic!("failed to run `{cargo} build -p forge-web --bin forge`: {e}")); |
| 36 | assert!( |
| 37 | output.status.success(), |
| 38 | "`{cargo} build -p forge-web --bin forge` failed ({})", |
| 39 | output.status |
| 40 | ); |
| 41 | let stdout = String::from_utf8(output.stdout).expect("cargo output is UTF-8"); |
| 42 | stdout |
| 43 | .lines() |
| 44 | .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok()) |
| 45 | .find(|msg| msg["reason"] == "compiler-artifact" && msg["target"]["name"] == "forge") |
| 46 | .and_then(|msg| msg["executable"].as_str().map(str::to_owned)) |
| 47 | .unwrap_or_else(|| panic!("cargo build reported no executable for the forge binary")) |
| 48 | } |
| 49 | |
| 50 | const READY_TIMEOUT: Duration = Duration::from_secs(30); |
| 51 | const MAX_LAUNCH_ATTEMPTS: u32 = 5; |
| 52 | |
| 53 | pub struct Server(pub Child); |
| 54 | |
| 55 | impl Drop for Server { |
| 56 | fn drop(&mut self) { |
| 57 | let _ = self.0.kill(); |
| 58 | let _ = self.0.wait(); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 63 | pub struct Ports { |
| 64 | pub http: u16, |
| 65 | pub ssh: u16, |
| 66 | pub content: u16, |
| 67 | } |
| 68 | |
| 69 | pub fn input_value(body: &str, name: &str) -> String { |
| 70 | let doc = scraper::Html::parse_document(body); |
| 71 | let selector = scraper::Selector::parse(&format!("input[name=\"{name}\"]")).expect("selector"); |
| 72 | doc.select(&selector) |
| 73 | .next() |
| 74 | .and_then(|el| el.value().attr("value")) |
| 75 | .unwrap_or_else(|| panic!("no input named {name} on page")) |
| 76 | .to_owned() |
| 77 | } |
| 78 | |
| 79 | pub fn first_text(body: &str, selector: &str) -> String { |
| 80 | let doc = scraper::Html::parse_document(body); |
| 81 | let selector = scraper::Selector::parse(selector).expect("selector"); |
| 82 | doc.select(&selector) |
| 83 | .next() |
| 84 | .unwrap_or_else(|| panic!("no element matches {selector:?}")) |
| 85 | .text() |
| 86 | .collect::<String>() |
| 87 | .trim() |
| 88 | .to_owned() |
| 89 | } |
| 90 | |
| 91 | pub fn form_action(body: &str, suffix: &str) -> String { |
| 92 | let doc = scraper::Html::parse_document(body); |
| 93 | let selector = scraper::Selector::parse("form").expect("selector"); |
| 94 | doc.select(&selector) |
| 95 | .filter_map(|el| el.value().attr("action")) |
| 96 | .find(|action| action.ends_with(suffix)) |
| 97 | .unwrap_or_else(|| panic!("no form ending in {suffix} on page")) |
| 98 | .to_owned() |
| 99 | } |
| 100 | |
| 101 | pub fn attr_values(body: &str, selector: &str, attr: &str) -> Vec<String> { |
| 102 | let doc = scraper::Html::parse_document(body); |
| 103 | let selector = scraper::Selector::parse(selector).expect("selector"); |
| 104 | doc.select(&selector) |
| 105 | .filter_map(|el| el.value().attr(attr).map(str::to_owned)) |
| 106 | .collect() |
| 107 | } |
| 108 | |
| 109 | pub fn element_texts(body: &str, selector: &str) -> Vec<String> { |
| 110 | let doc = scraper::Html::parse_document(body); |
| 111 | let selector = scraper::Selector::parse(selector).expect("selector"); |
| 112 | doc.select(&selector) |
| 113 | .map(|el| el.text().collect::<String>()) |
| 114 | .collect() |
| 115 | } |
| 116 | |
| 117 | pub fn attr_of(body: &str, selector: &str, attr: &str) -> Option<String> { |
| 118 | let doc = scraper::Html::parse_document(body); |
| 119 | let selector = scraper::Selector::parse(selector).expect("selector"); |
| 120 | doc.select(&selector) |
| 121 | .next() |
| 122 | .and_then(|el| el.value().attr(attr)) |
| 123 | .map(str::to_owned) |
| 124 | } |
| 125 | |
| 126 | pub fn text_or_empty(body: &str, selector: &str) -> String { |
| 127 | let doc = scraper::Html::parse_document(body); |
| 128 | let selector = scraper::Selector::parse(selector).expect("selector"); |
| 129 | doc.select(&selector) |
| 130 | .next() |
| 131 | .map(|el| el.text().collect::<String>().trim().to_owned()) |
| 132 | .unwrap_or_default() |
| 133 | } |
| 134 | |
| 135 | pub fn temp_dir(prefix: &str) -> tempfile::TempDir { |
| 136 | tempfile::Builder::new() |
| 137 | .prefix(prefix) |
| 138 | .tempdir_in("/tmp") |
| 139 | .expect("temp dir") |
| 140 | } |
| 141 | |
| 142 | pub async fn assert_quiet(res: &mut reqwest::Response, what: &str) { |
| 143 | let got = tokio::time::timeout(Duration::from_secs(2), res.chunk()).await; |
| 144 | assert!(got.is_err(), "{what}: the stream sent an event"); |
| 145 | } |
| 146 | |
| 147 | pub fn free_port() -> u16 { |
| 148 | std::net::TcpListener::bind("127.0.0.1:0") |
| 149 | .expect("bind free port") |
| 150 | .local_addr() |
| 151 | .expect("local addr") |
| 152 | .port() |
| 153 | } |
| 154 | |
| 155 | pub fn pick_ports() -> Ports { |
| 156 | let mut ports: Vec<u16> = Vec::new(); |
| 157 | while ports.len() < 3 { |
| 158 | let port = free_port(); |
| 159 | if !ports.contains(&port) { |
| 160 | ports.push(port); |
| 161 | } |
| 162 | } |
| 163 | Ports { |
| 164 | http: ports[0], |
| 165 | ssh: ports[1], |
| 166 | content: ports[2], |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | pub fn tool_on_path(name: &str) -> bool { |
| 171 | Command::new(name) |
| 172 | .stdin(Stdio::null()) |
| 173 | .stdout(Stdio::null()) |
| 174 | .stderr(Stdio::null()) |
| 175 | .status() |
| 176 | .is_ok() |
| 177 | } |
| 178 | |
| 179 | pub fn write_config_with(dir: &Path, ports: Ports, extra: &str) -> PathBuf { |
| 180 | let d = dir.display(); |
| 181 | let Ports { |
| 182 | http: http_port, |
| 183 | ssh: ssh_port, |
| 184 | content: content_port, |
| 185 | } = ports; |
| 186 | let text = format!( |
| 187 | "database = \"{d}/forge.db\"\n\ |
| 188 | data_dir = \"{d}\"\n\ |
| 189 | listen = \"127.0.0.1:{http_port}\"\n\ |
| 190 | base_url = \"http://127.0.0.1:{http_port}\"\n\ |
| 191 | user_content_base_url = \"http://127.0.0.1:{content_port}\"\n\ |
| 192 | user_content_listen = \"127.0.0.1:{content_port}\"\n\ |
| 193 | ssh_listen = \"127.0.0.1:{ssh_port}\"\n\ |
| 194 | ssh_public_host = \"127.0.0.1\"\n\ |
| 195 | ssh_public_port = {ssh_port}\n\ |
| 196 | registration = \"closed\"\n\ |
| 197 | ssh_auth_rejection_secs = 0\n{extra}" |
| 198 | ); |
| 199 | let path = dir.join("forge.toml"); |
| 200 | fs::write(&path, text).expect("write config"); |
| 201 | path |
| 202 | } |
| 203 | |
| 204 | pub const FAST_CLAIMS: &str = "[ci]\nclaim_wait_ms = 50\n"; |
| 205 | |
| 206 | pub fn git(cwd: &Path, args: &[&str]) -> Output { |
| 207 | git_env(cwd, args, &[]) |
| 208 | } |
| 209 | |
| 210 | pub fn ok(out: &Output, what: &str) { |
| 211 | assert!(out.status.success(), "{what} failed:\n{}", describe(out)); |
| 212 | } |
| 213 | |
| 214 | pub fn path_str(path: &Path) -> &str { |
| 215 | path.to_str().expect("utf-8 path") |
| 216 | } |
| 217 | |
| 218 | pub fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { |
| 219 | let mut cmd = Command::new("git"); |
| 220 | cmd.current_dir(cwd) |
| 221 | .args(["-c", "credential.helper="]) |
| 222 | .args(args) |
| 223 | .env("GIT_TERMINAL_PROMPT", "0"); |
| 224 | for (key, value) in env { |
| 225 | cmd.env(key, value); |
| 226 | } |
| 227 | cmd.output().expect("run git") |
| 228 | } |
| 229 | |
| 230 | pub fn git_text(cwd: &Path, args: &[&str]) -> String { |
| 231 | git_text_env(cwd, args, &[]) |
| 232 | } |
| 233 | |
| 234 | pub fn git_text_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String { |
| 235 | let out = git_env(cwd, args, env); |
| 236 | assert!( |
| 237 | out.status.success(), |
| 238 | "git {args:?} failed:\n{}", |
| 239 | describe(&out) |
| 240 | ); |
| 241 | String::from_utf8_lossy(&out.stdout).trim().to_owned() |
| 242 | } |
| 243 | |
| 244 | pub fn set_identity(repo: &Path) { |
| 245 | ok( |
| 246 | &git(repo, &["config", "user.name", "tahinli"]), |
| 247 | "set user.name", |
| 248 | ); |
| 249 | ok( |
| 250 | &git(repo, &["config", "user.email", "tahinli@example.com"]), |
| 251 | "set user.email", |
| 252 | ); |
| 253 | } |
| 254 | |
| 255 | pub fn head_sha(repo: &Path) -> String { |
| 256 | git_text(repo, &["rev-parse", "HEAD"]) |
| 257 | } |
| 258 | |
| 259 | pub fn commit_file(repo: &Path, name: &str, content: &str, message: &str) -> String { |
| 260 | let file = repo.join(name); |
| 261 | fs::create_dir_all(file.parent().expect("parent")).expect("create dir"); |
| 262 | fs::write(&file, content).expect("write file"); |
| 263 | set_identity(repo); |
| 264 | ok(&git(repo, &["add", name]), "git add"); |
| 265 | ok( |
| 266 | &git( |
| 267 | repo, |
| 268 | &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], |
| 269 | ), |
| 270 | "git commit", |
| 271 | ); |
| 272 | head_sha(repo) |
| 273 | } |
| 274 | |
| 275 | pub fn commit(repo: &Path, file: &str, contents: &str, message: &str, who: (&str, &str)) -> String { |
| 276 | let (name, email) = who; |
| 277 | let path = repo.join(file); |
| 278 | if let Some(parent) = path.parent() { |
| 279 | fs::create_dir_all(parent).expect("create dir"); |
| 280 | } |
| 281 | fs::write(&path, contents).expect("write file"); |
| 282 | git_text(repo, &["add", file]); |
| 283 | git_text_env( |
| 284 | repo, |
| 285 | &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], |
| 286 | &[ |
| 287 | ("GIT_AUTHOR_NAME", name), |
| 288 | ("GIT_AUTHOR_EMAIL", email), |
| 289 | ("GIT_COMMITTER_NAME", name), |
| 290 | ("GIT_COMMITTER_EMAIL", email), |
| 291 | ], |
| 292 | ); |
| 293 | git_text(repo, &["rev-parse", "HEAD"]) |
| 294 | } |
| 295 | |
| 296 | pub fn clone(url: &str, into: &Path) -> PathBuf { |
| 297 | let parent = into.parent().expect("clone target has a parent"); |
| 298 | git_text(parent, &["clone", "-q", url, path_str(into)]); |
| 299 | into.to_path_buf() |
| 300 | } |
| 301 | |
| 302 | pub async fn create_token(http: &Http, session: &str, name: &str) -> String { |
| 303 | let page = http.get_cookie("/settings/keys", session).await; |
| 304 | assert_eq!(page.status, 200, "GET /settings/keys"); |
| 305 | let csrf = input_value(&page.body, "csrf"); |
| 306 | let res = http |
| 307 | .post_form( |
| 308 | "/settings/tokens", |
| 309 | &[("csrf", &csrf), ("name", name), ("expires", "30")], |
| 310 | Some(session), |
| 311 | ) |
| 312 | .await; |
| 313 | assert_eq!(res.status, 200, "create token: {}", res.body); |
| 314 | let doc = scraper::Html::parse_document(&res.body); |
| 315 | let selector = scraper::Selector::parse("pre.code code").expect("selector"); |
| 316 | let token: String = doc |
| 317 | .select(&selector) |
| 318 | .next() |
| 319 | .expect("token shown after creation") |
| 320 | .text() |
| 321 | .collect(); |
| 322 | let token = token.trim().to_owned(); |
| 323 | assert!(token.starts_with("forge_"), "unexpected token shape"); |
| 324 | token |
| 325 | } |
| 326 | |
| 327 | pub async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) { |
| 328 | let page = http.get_cookie("/new", session).await; |
| 329 | assert_eq!(page.status, 200, "GET /new"); |
| 330 | let csrf = input_value(&page.body, "csrf"); |
| 331 | let res = http |
| 332 | .post_form( |
| 333 | "/new", |
| 334 | &[ |
| 335 | ("csrf", &csrf), |
| 336 | ("name", name), |
| 337 | ("description", ""), |
| 338 | ("visibility", visibility), |
| 339 | ("default_branch", "main"), |
| 340 | ], |
| 341 | Some(session), |
| 342 | ) |
| 343 | .await; |
| 344 | assert_eq!(res.status, 303, "create repo {name}: {}", res.body); |
| 345 | assert_eq!( |
| 346 | res.location().as_deref(), |
| 347 | Some(format!("/tahinli/{name}").as_str()) |
| 348 | ); |
| 349 | } |
| 350 | |
| 351 | pub const PW: &str = "tahinli-password-123"; |
| 352 | |
| 353 | pub fn admin(config: &Path, args: &[&str]) -> Output { |
| 354 | let out = Command::new(bin()) |
| 355 | .arg("--config") |
| 356 | .arg(config) |
| 357 | .arg("admin") |
| 358 | .args(args) |
| 359 | .env("FORGE_PASSWORD", PW) |
| 360 | .output() |
| 361 | .expect("run admin command"); |
| 362 | assert!( |
| 363 | out.status.success(), |
| 364 | "admin {args:?} failed:\n{}", |
| 365 | describe(&out) |
| 366 | ); |
| 367 | out |
| 368 | } |
| 369 | |
| 370 | pub fn init_bare(data_dir: &Path, repo_id: &str) { |
| 371 | let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path"); |
| 372 | fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent"); |
| 373 | let out = Command::new("git") |
| 374 | .args(["init", "--bare", "--quiet", "--initial-branch=main"]) |
| 375 | .arg(&path) |
| 376 | .output() |
| 377 | .expect("run git init"); |
| 378 | assert!(out.status.success(), "git init --bare: {}", describe(&out)); |
| 379 | } |
| 380 | |
| 381 | pub fn describe(out: &Output) -> String { |
| 382 | format!( |
| 383 | "status: {}\nstdout: {}\nstderr: {}", |
| 384 | out.status, |
| 385 | String::from_utf8_lossy(&out.stdout), |
| 386 | String::from_utf8_lossy(&out.stderr) |
| 387 | ) |
| 388 | } |
| 389 | |
| 390 | pub async fn next_changed(res: &mut reqwest::Response, what: &str) { |
| 391 | let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk()) |
| 392 | .await |
| 393 | .unwrap_or_else(|_| panic!("no event after {what}")) |
| 394 | .expect("stream chunk") |
| 395 | .expect("stream still open"); |
| 396 | let text = String::from_utf8_lossy(&chunk); |
| 397 | assert!(text.contains("event: changed"), "{what}: {text}"); |
| 398 | } |
| 399 | |
| 400 | pub const TAHINLI_CMD: &[&str] = &["create-user", "tahinli", "--admin"]; |
| 401 | pub const BOB_CMD: &[&str] = &["create-user", "bob"]; |
| 402 | |
| 403 | pub fn provision(dir: &Path, extra: &str, admin_cmds: &[&[&str]]) -> (PathBuf, Ports) { |
| 404 | let ports = pick_ports(); |
| 405 | let config = write_config_with(dir, ports, extra); |
| 406 | for args in admin_cmds { |
| 407 | admin(&config, args); |
| 408 | } |
| 409 | (config, ports) |
| 410 | } |
| 411 | |
| 412 | pub async fn boot_forge(dir: &Path, extra: &str, admin_cmds: &[&[&str]]) -> (Server, Ports) { |
| 413 | let (_, ports) = provision(dir, extra, admin_cmds); |
| 414 | launch_with(dir, ports, extra).await |
| 415 | } |
| 416 | |
| 417 | pub async fn launch(dir: &Path, ports: Ports) -> (Server, Ports) { |
| 418 | launch_with(dir, ports, "").await |
| 419 | } |
| 420 | |
| 421 | pub async fn launch_with(dir: &Path, ports: Ports, extra: &str) -> (Server, Ports) { |
| 422 | let log_path = dir.join("serve.log"); |
| 423 | let mut ports = ports; |
| 424 | for attempt in 1..=MAX_LAUNCH_ATTEMPTS { |
| 425 | let config = write_config_with(dir, ports, extra); |
| 426 | let mut server = spawn(&config, &log_path); |
| 427 | match wait_ready(ports, &mut server, &log_path).await { |
| 428 | Ok(()) => return (server, ports), |
| 429 | Err(status) => { |
| 430 | let log = read_log(&log_path); |
| 431 | if attempt < MAX_LAUNCH_ATTEMPTS && bind_conflict(&log) { |
| 432 | ports = pick_ports(); |
| 433 | continue; |
| 434 | } |
| 435 | panic!("forge exited early ({status}):\n{log}"); |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | unreachable!("the last attempt either returns or panics") |
| 440 | } |
| 441 | |
| 442 | pub async fn relaunch(config: &Path, log_path: &Path, ports: Ports) -> Server { |
| 443 | let mut server = spawn(config, log_path); |
| 444 | match wait_ready(ports, &mut server, log_path).await { |
| 445 | Ok(()) => server, |
| 446 | Err(status) => panic!( |
| 447 | "forge exited early on restart ({status}):\n{}", |
| 448 | read_log(log_path) |
| 449 | ), |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | fn spawn(config: &Path, log_path: &Path) -> Server { |
| 454 | let log = fs::File::create(log_path).expect("log file"); |
| 455 | let child = Command::new(bin()) |
| 456 | .arg("--config") |
| 457 | .arg(config) |
| 458 | .arg("serve") |
| 459 | .stdin(Stdio::null()) |
| 460 | .stdout(Stdio::from(log.try_clone().expect("clone log"))) |
| 461 | .stderr(Stdio::from(log)) |
| 462 | .spawn() |
| 463 | .expect("spawn forge serve"); |
| 464 | Server(child) |
| 465 | } |
| 466 | |
| 467 | async fn wait_ready(ports: Ports, server: &mut Server, log: &Path) -> Result<(), ExitStatus> { |
| 468 | let client = reqwest::Client::builder() |
| 469 | .timeout(Duration::from_secs(2)) |
| 470 | .build() |
| 471 | .expect("probe client"); |
| 472 | let app = format!("http://127.0.0.1:{}/healthz", ports.http); |
| 473 | let raw = format!("http://127.0.0.1:{}/healthz", ports.content); |
| 474 | let deadline = Instant::now() + READY_TIMEOUT; |
| 475 | let mut delay = Duration::from_millis(10); |
| 476 | loop { |
| 477 | if let Some(status) = server.0.try_wait().expect("poll forge-web") { |
| 478 | return Err(status); |
| 479 | } |
| 480 | if probe(&client, &app).await && probe(&client, &raw).await && ssh_open(ports.ssh) { |
| 481 | return Ok(()); |
| 482 | } |
| 483 | if Instant::now() >= deadline { |
| 484 | panic!( |
| 485 | "forge was not ready within {READY_TIMEOUT:?}:\n{}", |
| 486 | read_log(log) |
| 487 | ); |
| 488 | } |
| 489 | tokio::time::sleep(delay).await; |
| 490 | delay = (delay * 2).min(Duration::from_millis(250)); |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | async fn probe(client: &reqwest::Client, url: &str) -> bool { |
| 495 | matches!(client.get(url).send().await, Ok(res) if res.status() == reqwest::StatusCode::OK) |
| 496 | } |
| 497 | |
| 498 | fn ssh_open(port: u16) -> bool { |
| 499 | TcpStream::connect(("127.0.0.1", port)).is_ok() |
| 500 | } |
| 501 | |
| 502 | fn read_log(log: &Path) -> String { |
| 503 | fs::read_to_string(log).unwrap_or_default() |
| 504 | } |
| 505 | |
| 506 | fn bind_conflict(log: &str) -> bool { |
| 507 | let log = log.to_ascii_lowercase(); |
| 508 | log.contains("address already in use") |
| 509 | || log.contains("addrinuse") |
| 510 | || log.contains("os error 98") |
| 511 | || log.contains("os error 48") |
| 512 | || log.contains("os error 10048") |
| 513 | } |