char/sorcery

static-files based git repo viewer

git clone https://git.t4t.associates/char/sorcery

Charlotte Somkeep daemon test socket paths within SUN_LEN4a707c3

main
5.5 KiB168 linesraw
1use std::fs;
2use std::io::{BufRead, BufReader, Read, Write};
3use std::os::unix::net::UnixStream;
4use std::path::{Path, PathBuf};
5use std::process::{Child, Command, Stdio};
6use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
7
8use anyhow::{Context, Result, bail};
9
10struct TestDir(PathBuf);
11
12impl TestDir {
13    fn new() -> Result<Self> {
14        // long TMPDIRs like unsandboxed Nix build dirs
15        // can exceed max path size limits so we'll use /tmp here
16        // if we'd overshoot, but use the regular tmpdir instead
17        let temp = std::env::temp_dir();
18        let base = if temp.as_os_str().len() > 72 && Path::new("/tmp").is_dir() {
19            PathBuf::from("/tmp")
20        } else {
21            temp
22        };
23        let pid = std::process::id();
24        for attempt in 0u32..64 {
25            let nanos = SystemTime::now().duration_since(UNIX_EPOCH)?.subsec_nanos();
26            let path = base.join(format!("s-{pid:x}-{:x}", nanos.wrapping_add(attempt)));
27            match fs::create_dir(&path) {
28                Ok(()) => return Ok(Self(path)),
29                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
30                Err(error) => return Err(error.into()),
31            }
32        }
33        bail!("could not create test directory in {}", base.display());
34    }
35}
36
37impl Drop for TestDir {
38    fn drop(&mut self) {
39        let _ = fs::remove_dir_all(&self.0);
40    }
41}
42
43struct Daemon(Child);
44
45impl Drop for Daemon {
46    fn drop(&mut self) {
47        if self.0.try_wait().ok().flatten().is_none() {
48            let _ = Command::new("kill")
49                .arg("-TERM")
50                .arg(self.0.id().to_string())
51                .status();
52            let _ = self.0.wait();
53        }
54    }
55}
56
57fn git(repo: &Path, args: &[&str]) -> Result<()> {
58    let status = Command::new("git")
59        .arg("-C")
60        .arg(repo)
61        .args(args)
62        .env("GIT_AUTHOR_NAME", "test")
63        .env("GIT_AUTHOR_EMAIL", "test@example.com")
64        .env("GIT_COMMITTER_NAME", "test")
65        .env("GIT_COMMITTER_EMAIL", "test@example.com")
66        .stdout(Stdio::null())
67        .status()?;
68    if !status.success() {
69        bail!("git {args:?} exited with {status}");
70    }
71    Ok(())
72}
73
74fn refresh(socket: &Path, path: &Path) -> Result<String> {
75    let mut stream = UnixStream::connect(socket)?;
76    stream.set_read_timeout(Some(Duration::from_secs(30)))?;
77    writeln!(stream, "{}", path.display())?;
78    let mut reply = String::new();
79    BufReader::new(stream).read_line(&mut reply)?;
80    Ok(reply)
81}
82
83fn http(socket: &Path, path: &str) -> Result<String> {
84    let mut stream = UnixStream::connect(socket)?;
85    stream.set_read_timeout(Some(Duration::from_secs(10)))?;
86    write!(
87        stream,
88        "GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"
89    )?;
90    let mut response = String::new();
91    stream.read_to_string(&mut response)?;
92    Ok(response)
93}
94
95#[test]
96fn refreshes_published_repositories_and_reports_their_urls() -> Result<()> {
97    let root = TestDir::new()?;
98    let repo = root.0.join("repos/alice/thing");
99    fs::create_dir_all(&repo)?;
100    git(&repo, &["init", "-q", "-b", "main"])?;
101    fs::write(repo.join("README"), "hello")?;
102    git(&repo, &["add", "README"])?;
103    git(&repo, &["commit", "-q", "-m", "initial"])?;
104
105    let socket = root.0.join("http.sock");
106    let control = root.0.join("control.sock");
107    let cache = root.0.join("cache");
108    let mut command = Command::new(env!("CARGO_BIN_EXE_sorceryd"));
109    for (key, _) in std::env::vars_os() {
110        if key.to_string_lossy().starts_with("SORCERY_") {
111            command.env_remove(key);
112        }
113    }
114    let mut daemon = Daemon(
115        command
116            .arg("serve")
117            .arg("--config")
118            .arg("/dev/null")
119            .arg("--repositories")
120            .arg(root.0.join("repos"))
121            .arg("--cache")
122            .arg(&cache)
123            .arg("--socket")
124            .arg(&socket)
125            .arg("--control-socket")
126            .arg(&control)
127            .arg("--instance-name=test")
128            .arg("--clone-url-base=https://git.example")
129            .arg("--x-accel=false")
130            .stdout(Stdio::null())
131            .spawn()?,
132    );
133    let deadline = Instant::now() + Duration::from_secs(30);
134    while !socket.exists() || !control.exists() {
135        if let Some(status) = daemon.0.try_wait()? {
136            bail!("daemon exited with {status}");
137        }
138        if Instant::now() >= deadline {
139            bail!("daemon sockets did not appear");
140        }
141        std::thread::sleep(Duration::from_millis(20));
142    }
143    assert_eq!(
144        refresh(&control, &repo)?,
145        "ok https://git.example/alice/thing\n"
146    );
147    assert_eq!(refresh(&control, &root.0.join("repos/alice"))?, "ok\n");
148    assert!(refresh(&control, &root.0.join("missing"))?.starts_with("error "));
149    assert!(cache.join("alice/thing/.sorcery-state").is_file());
150    let page = http(&socket, "/alice/thing/")?;
151    assert!(page.starts_with("HTTP/1.1 200"), "{page}");
152    assert!(page.contains("alice/thing"));
153    let health = http(&socket, "/-/health")?;
154    assert!(
155        health.starts_with("HTTP/1.1 200") && health.contains("ok\n"),
156        "{health}"
157    );
158
159    let status = Command::new("kill")
160        .arg("-TERM")
161        .arg(daemon.0.id().to_string())
162        .status()?;
163    assert!(status.success());
164    let status = daemon.0.wait().context("waiting for daemon shutdown")?;
165    assert!(status.success(), "daemon exited with {status}");
166    assert!(!socket.exists() && !control.exists());
167    Ok(())
168}