use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use super::*;
static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
struct EnvGuard {
_data_dir: tempfile::TempDir,
}
impl EnvGuard {
fn isolated() -> Self {
let data_dir = tempfile::tempdir().expect("data dir");
unsafe {
std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, data_dir.path());
}
Self {
_data_dir: data_dir,
}
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
unsafe {
std::env::remove_var(trusty_common::DATA_DIR_OVERRIDE_ENV);
}
}
}
fn stub_daemon_socket(dir: &Path, binding: Option<serde_json::Value>) -> PathBuf {
let socket = dir.join("tcode.sock");
stub_daemon_at(&socket, binding);
socket
}
fn stub_daemon_at(socket: &Path, binding: Option<serde_json::Value>) {
stub_daemon_with_build(socket, binding, Some(trusty_code::build_info::GIT_HASH));
}
fn stub_daemon_with_build(
socket: &Path,
binding: Option<serde_json::Value>,
build: Option<&'static str>,
) {
stub_daemon_full(socket, binding, build, trusty_code::VERSION, false);
}
fn stub_daemon_full(
socket: &Path,
binding: Option<serde_json::Value>,
build: Option<&'static str>,
version: &'static str,
fail_health: bool,
) {
if socket.exists() {
std::fs::remove_file(socket).expect("clear the stale stub socket");
}
let listener = trusty_common::uds::bind_hardened(socket).expect("bind the stub socket");
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let binding = binding.clone();
tokio::spawn(async move {
let mut reader = BufReader::new(stream);
let mut line = String::new();
if reader.read_line(&mut line).await.unwrap_or(0) == 0 {
return;
}
let request: serde_json::Value = match serde_json::from_str(&line) {
Ok(request) => request,
Err(_) => return,
};
if fail_health {
let body = format!(
"{}\n",
serde_json::json!({
"jsonrpc": "2.0",
"id": request["id"].clone(),
"error": {"code": -32603, "message": "health is broken"},
})
);
let _ = reader.get_mut().write_all(body.as_bytes()).await;
let _ = reader.get_mut().flush().await;
return;
}
let mut result = serde_json::json!({
"server": "tcode", "status": "ok", "pid": 4242, "version": version,
});
if let Some(build) = build {
result["build"] = serde_json::json!(build);
}
if let Some(binding) = binding {
result["binding"] = binding;
}
let body = format!(
"{}\n",
serde_json::json!({
"jsonrpc": "2.0",
"id": request["id"].clone(),
"result": result,
})
);
let _ = reader.get_mut().write_all(body.as_bytes()).await;
let _ = reader.get_mut().flush().await;
});
}
});
}
fn binding_json(root: Option<&Path>) -> serde_json::Value {
trusty_code::binding::ProjectBinding::resolve(root.map(Path::to_path_buf))
.expect("must bind")
.to_json()
}
fn stub_binary(dir: &Path, name: &str, body: &str) -> PathBuf {
let staging = dir.join(format!(".{name}.tmp"));
write_stub(&staging, body);
let script = dir.join(name);
std::fs::rename(&staging, &script).expect("move the stub into place");
script
}
fn write_stub(staging: &Path, body: &str) {
trusty_common::exec_stub::write_executable(staging, format!("#!/bin/sh\n{body}\n"))
.unwrap_or_else(|e| panic!("stub writer failed for {staging:?}: {e}"));
}
fn stable_stub_root() -> PathBuf {
let uid = unsafe { libc::getuid() };
std::env::temp_dir().join(format!("trusty-test-stubs-{uid}"))
}
fn stable_stub(name: &str, body: &str) -> PathBuf {
use std::os::unix::fs::DirBuilderExt;
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
let script = stable_stub_path(name, body);
let dir = script.parent().expect("stub dir").to_path_buf();
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(&dir)
.expect("create the stable stub dir");
assert_private(&stable_stub_root());
assert_private(&dir);
if std::fs::symlink_metadata(&script).is_err() {
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
let staging = dir.join(format!(".{name}.{}.{seq}.tmp", std::process::id()));
write_stub(&staging, body);
std::fs::rename(&staging, &script).expect("publish the stable stub");
}
assert_private(&script);
let text = std::fs::read_to_string(&script).expect("read the stable stub");
assert_eq!(
text,
format!("#!/bin/sh\n{body}\n"),
"{script:?} does not hold the stub body; refusing to run it"
);
script
}
fn stable_stub_path(name: &str, body: &str) -> PathBuf {
use sha2::{Digest, Sha256};
let digest = Sha256::new()
.chain_update(name)
.chain_update([0u8])
.chain_update(body)
.finalize();
let key: String = digest[..12].iter().map(|b| format!("{b:02x}")).collect();
stable_stub_root().join(key).join(name)
}
fn assert_private(path: &Path) {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::symlink_metadata(path).expect("stat a stable stub path");
let uid = unsafe { libc::getuid() };
assert!(!meta.file_type().is_symlink(), "{path:?} is a symlink");
assert_eq!(meta.uid(), uid, "{path:?} belongs to another user");
assert_eq!(
meta.mode() & 0o022,
0,
"{path:?} is group- or world-writable"
);
}
struct SleepingStub {
path: PathBuf,
argv_log: PathBuf,
pid_log: PathBuf,
}
impl SleepingStub {
fn new(dir: &Path) -> Self {
let argv_log = dir.join("argv");
let pid_log = dir.join("pid");
let path = stub_binary(
dir,
"tcode-sleep",
&format!(
"echo \"$@\" >> {}\necho $$ >> {}\nsleep 300",
argv_log.display(),
pid_log.display()
),
);
Self {
path,
argv_log,
pid_log,
}
}
async fn argv(&self) -> String {
wait_for_record(&self.argv_log, "argv").await
}
async fn pid(&self) -> u32 {
wait_for_record(&self.pid_log, "pid")
.await
.trim()
.parse::<u32>()
.expect("the stub records its pid as a bare integer")
}
}
impl Drop for SleepingStub {
fn drop(&mut self) {
if let Ok(raw) = std::fs::read_to_string(&self.pid_log) {
raw.lines()
.filter_map(|line| line.trim().parse::<u32>().ok())
.for_each(kill);
}
}
}
async fn wait_for_record(path: &Path, label: &str) -> String {
for _ in 0..200 {
if let Ok(raw) = std::fs::read_to_string(path)
&& !raw.trim().is_empty()
{
return raw;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("the spawned stub never recorded its {label} at {path:?}");
}
fn bind_socket_after_spawn(stub: &SleepingStub, dir: &Path, binding: serde_json::Value) {
bind_at_after_spawn(stub, dir.join("tcode.sock"), binding);
}
fn bind_at_after_spawn(stub: &SleepingStub, socket: PathBuf, binding: serde_json::Value) {
bind_once_argv_has(&stub.argv_log, "", socket, Some(binding));
}
fn bind_once_argv_has(
argv_log: &Path,
needle: &'static str,
socket: PathBuf,
binding: Option<serde_json::Value>,
) {
let argv_log = argv_log.to_path_buf();
tokio::spawn(async move {
for _ in 0..200 {
if std::fs::read_to_string(&argv_log)
.is_ok_and(|raw| !raw.trim().is_empty() && raw.contains(needle))
{
stub_daemon_at(&socket, binding);
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
});
}
fn mute_daemon_at(socket: &Path) {
let listener = trusty_common::uds::bind_hardened(socket).expect("bind the mute socket");
tokio::spawn(async move { while listener.accept().await.is_ok() {} });
}
fn marker_stub(dir: &Path, marker: &Path) -> PathBuf {
assert_eq!(
marker,
dir.join("spawned"),
"the marker sits beside the link"
);
let script = stable_stub("tcode-marker", "touch \"${0%/*}/spawned\"\nsleep 300");
let link = dir.join("tcode-marker");
std::os::unix::fs::symlink(&script, &link).expect("link the marker stub");
link
}
fn is_alive(pid: u32) -> bool {
unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
}
fn kill(pid: u32) {
unsafe {
libc::kill(pid as libc::pid_t, libc::SIGKILL);
}
}
#[tokio::test]
async fn attaches_to_a_live_daemon_without_spawning() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let project = tempfile::tempdir().expect("project");
let canonical = project.path().canonicalize().expect("canonicalize");
let sock_dir = tempfile::tempdir().expect("socket dir");
let socket = stub_daemon_socket(sock_dir.path(), Some(binding_json(Some(&canonical))));
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let resolved = ensure_daemon_with(Some(&canonical), &stub, &socket)
.await
.expect("must attach to the live daemon");
assert_eq!(resolved, socket);
assert!(
!marker.exists(),
"must not have spawned anything: {marker:?}"
);
}
#[tokio::test]
async fn attaches_to_a_projectless_daemon_when_projectless() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let sock_dir = tempfile::tempdir().expect("socket dir");
let socket = stub_daemon_socket(sock_dir.path(), Some(binding_json(None)));
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let resolved = ensure_daemon_with(None, &stub, &socket)
.await
.expect("a projectless TUI must attach to a projectless daemon");
assert_eq!(resolved, socket);
assert!(!marker.exists(), "must not have spawned anything");
}
#[tokio::test]
async fn refuses_a_daemon_from_a_different_build() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let project = tempfile::tempdir().expect("project");
let canonical = project.path().canonicalize().expect("canonicalize");
for (build, label) in [
(Some("0123abc-stale"), "0123abc-stale"),
(None, "<unreported>"),
] {
let sock_dir = tempfile::tempdir().expect("socket dir");
let socket = sock_dir.path().join("tcode.sock");
stub_daemon_with_build(&socket, Some(binding_json(Some(&canonical))), build);
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let err = ensure_daemon_with(Some(&canonical), &stub, &socket)
.await
.expect_err("a daemon from another build must be refused")
.to_string();
for needle in [
label,
trusty_code::build_info::GIT_HASH,
"4242",
"tcode tui",
] {
assert!(err.contains(needle), "refusal must name {needle:?}: {err}");
}
assert!(!marker.exists(), "a refusal must not spawn anything");
}
}
#[tokio::test]
async fn refuses_a_different_version_when_the_builds_match() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let project = tempfile::tempdir().expect("project");
let canonical = project.path().canonicalize().expect("canonicalize");
let sock_dir = tempfile::tempdir().expect("socket dir");
let socket = sock_dir.path().join("tcode.sock");
stub_daemon_full(
&socket,
Some(binding_json(Some(&canonical))),
Some(trusty_code::build_info::GIT_HASH),
"0.0.1-stale",
false,
);
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let err = ensure_daemon_with(Some(&canonical), &stub, &socket)
.await
.expect_err("a daemon of another version must be refused")
.to_string();
for needle in ["0.0.1-stale", trusty_code::VERSION, "4242"] {
assert!(err.contains(needle), "refusal must name {needle:?}: {err}");
}
assert!(!marker.exists(), "a refusal must not spawn anything");
}
#[tokio::test]
async fn a_failed_health_call_is_not_reported_as_an_unreported_build() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let sock_dir = tempfile::tempdir().expect("socket dir");
let socket = sock_dir.path().join("tcode.sock");
stub_daemon_full(
&socket,
None,
Some(trusty_code::build_info::GIT_HASH),
trusty_code::VERSION,
true,
);
let err = check_build(&socket)
.await
.expect_err("a daemon that cannot answer health is refused")
.to_string();
assert!(err.contains("`health` call failed"), "wrong message: {err}");
assert!(!err.contains("<unreported>"), "wrong message: {err}");
}
fn own_socket(socket: &Path, project: Option<&Path>) -> PathBuf {
trusty_code::serve::uds::project_socket_path(socket, project)
}
#[tokio::test]
async fn a_second_project_starts_its_own_daemon_beside_the_first() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let their_project = tempfile::tempdir().expect("their project");
let our_project = tempfile::tempdir().expect("our project");
let theirs = their_project.path().canonicalize().expect("canonicalize");
let ours = our_project.path().canonicalize().expect("canonicalize");
for wanted in [Some(ours.as_path()), None] {
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = stub_daemon_socket(sock_dir.path(), Some(binding_json(Some(&theirs))));
let own = own_socket(&shared, wanted);
drop(std::os::unix::net::UnixListener::bind(&own).expect("leave a stale own socket"));
let dir = tempfile::tempdir().expect("tempdir");
let stub = SleepingStub::new(dir.path());
bind_at_after_spawn(&stub, own.clone(), binding_json(wanted));
let resolved = ensure_daemon_with(wanted, &stub.path, &shared).await;
assert!(
matches!(&resolved, Ok(path) if *path == own && *path != shared),
"project {wanted:?} must get its own daemon on {own:?}, not attach to or be \
refused by the other project's daemon on {shared:?}: {resolved:?}"
);
let argv = stub.argv().await;
assert!(
argv.contains("--project-socket")
&& !argv.contains("--port")
&& !argv.contains("--http"),
"the second project's daemon must bind its own socket and no TCP port: {argv}"
);
assert_eq!(
argv.contains("--project "),
wanted.is_some(),
"--project must be forwarded exactly when the client has one: {argv}"
);
}
}
#[tokio::test]
async fn a_second_project_reuses_its_own_running_daemon() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let their_project = tempfile::tempdir().expect("their project");
let our_project = tempfile::tempdir().expect("our project");
let theirs = their_project.path().canonicalize().expect("canonicalize");
let ours = our_project.path().canonicalize().expect("canonicalize");
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = stub_daemon_socket(sock_dir.path(), Some(binding_json(Some(&theirs))));
let own = own_socket(&shared, Some(&ours));
stub_daemon_at(&own, Some(binding_json(Some(&ours))));
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let resolved = ensure_daemon_with(Some(&ours), &stub, &shared).await;
assert!(
matches!(&resolved, Ok(path) if *path == own),
"must reuse this project's running daemon on {own:?}: {resolved:?}"
);
assert!(!marker.exists(), "must not have spawned anything");
}
#[tokio::test]
async fn refuses_another_projects_daemon_on_this_projects_own_socket() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let their_project = tempfile::tempdir().expect("their project");
let our_project = tempfile::tempdir().expect("our project");
let theirs = their_project.path().canonicalize().expect("canonicalize");
let ours = our_project.path().canonicalize().expect("canonicalize");
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = sock_dir.path().join("tcode.sock");
let own = own_socket(&shared, Some(&ours));
stub_daemon_at(&own, Some(binding_json(Some(&theirs))));
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let err = ensure_daemon_with(Some(&ours), &stub, &shared)
.await
.expect_err("a daemon on another project must not be attached to");
let rendered = format!("{err:#}");
assert!(
rendered.contains(&theirs.display().to_string()),
"error must name the daemon's project: {rendered}"
);
assert!(
rendered.contains(&ours.display().to_string()),
"error must name the requested project: {rendered}"
);
assert!(
!marker.exists(),
"must not start a competing daemon on a socket already bound: {rendered}"
);
}
#[tokio::test]
async fn refuses_a_third_projects_daemon_that_answers_on_our_socket_after_our_spawn() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let their_project = tempfile::tempdir().expect("their project");
let our_project = tempfile::tempdir().expect("our project");
let third_project = tempfile::tempdir().expect("third project");
let theirs = their_project.path().canonicalize().expect("canonicalize");
let ours = our_project.path().canonicalize().expect("canonicalize");
let third = third_project.path().canonicalize().expect("canonicalize");
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = stub_daemon_socket(sock_dir.path(), Some(binding_json(Some(&theirs))));
let own = own_socket(&shared, Some(&ours));
let dir = tempfile::tempdir().expect("tempdir");
let stub = SleepingStub::new(dir.path());
bind_once_argv_has(
&stub.argv_log,
"--project-socket",
own.clone(),
Some(binding_json(Some(&third))),
);
let err = ensure_daemon_with(Some(&ours), &stub.path, &shared)
.await
.expect_err("a third project's daemon must not be attached to");
let rendered = format!("{err:#}");
assert!(
rendered.contains(&third.display().to_string()),
"error must name the project that answered on our socket: {rendered}"
);
assert!(
rendered.contains(&ours.display().to_string()),
"error must name the requested project: {rendered}"
);
let argv = stub.argv().await;
assert!(
argv.lines().count() == 1 && argv.contains("--project-socket"),
"exactly one own-socket spawn must have happened: {argv}"
);
}
fn assert_unverified_refusal(rendered: &str, socket: &Path) {
assert!(
rendered.contains(&socket.display().to_string()),
"the refusal must name the daemon's socket {socket:?}: {rendered}"
);
assert!(
rendered.contains("run `tcode tui` again"),
"the refusal must carry an actionable remedy: {rendered}"
);
assert!(
!rendered.to_lowercase().contains("stop"),
"the refusal must never tell the operator to stop a daemon: {rendered}"
);
}
#[tokio::test]
async fn refuses_an_unverifiable_shared_daemon_without_spawning() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let project = tempfile::tempdir().expect("project");
let ours = project.path().canonicalize().expect("canonicalize");
for wanted in [Some(ours.as_path()), None] {
for health_fails in [false, true] {
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = sock_dir.path().join("tcode.sock");
if health_fails {
mute_daemon_at(&shared);
} else {
stub_daemon_at(&shared, None);
}
let dir = tempfile::tempdir().expect("tempdir");
let stub = SleepingStub::new(dir.path());
bind_at_after_spawn(&stub, own_socket(&shared, wanted), binding_json(wanted));
let resolved = ensure_daemon_with(wanted, &stub.path, &shared).await;
let case = format!("wanted {wanted:?}, health fails: {health_fails}");
let rendered = match &resolved {
Err(e) => format!("{e:#}"),
Ok(path) => panic!("{case}: must refuse, not attach to {path:?}"),
};
assert_unverified_refusal(&rendered, &shared);
let argv = std::fs::read_to_string(&stub.argv_log).unwrap_or_default();
assert!(argv.is_empty(), "{case}: nothing may be spawned: {argv}");
assert!(
!argv.contains("--project-socket"),
"{case}: no daemon may start on the own socket: {argv}"
);
}
}
}
#[tokio::test]
async fn a_cold_start_race_lost_to_another_project_starts_our_own_daemon() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let their_project = tempfile::tempdir().expect("their project");
let our_project = tempfile::tempdir().expect("our project");
let theirs = their_project.path().canonicalize().expect("canonicalize");
let ours = our_project.path().canonicalize().expect("canonicalize");
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = sock_dir.path().join("tcode.sock");
let own = own_socket(&shared, Some(&ours));
let dir = tempfile::tempdir().expect("tempdir");
let stub = SleepingStub::new(dir.path());
let theirs_json = binding_json(Some(&theirs));
bind_once_argv_has(&stub.argv_log, "", shared.clone(), Some(theirs_json));
let ours_json = binding_json(Some(&ours));
bind_once_argv_has(
&stub.argv_log,
"--project-socket",
own.clone(),
Some(ours_json),
);
let resolved = ensure_daemon_with(Some(&ours), &stub.path, &shared).await;
assert!(
matches!(&resolved, Ok(path) if *path == own),
"after losing the shared socket to another project, this project must run \
on its own socket {own:?}: {resolved:?}"
);
let argv = stub.argv().await;
let spawns: Vec<&str> = argv.lines().collect();
assert!(
spawns.len() == 2
&& !spawns[0].contains("--project-socket")
&& spawns[1].contains("--project-socket"),
"one shared spawn, then one own-socket spawn: {argv}"
);
}
#[tokio::test]
async fn a_cold_start_race_lost_to_an_unverifiable_daemon_is_refused() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let project = tempfile::tempdir().expect("project");
let ours = project.path().canonicalize().expect("canonicalize");
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = sock_dir.path().join("tcode.sock");
let dir = tempfile::tempdir().expect("tempdir");
let stub = SleepingStub::new(dir.path());
bind_once_argv_has(&stub.argv_log, "", shared.clone(), None);
let err = ensure_daemon_with(Some(&ours), &stub.path, &shared)
.await
.expect_err("an unverifiable daemon must not be attached to");
assert_unverified_refusal(&format!("{err:#}"), &shared);
let argv = stub.argv().await;
assert!(
argv.lines().count() == 1 && !argv.contains("--project-socket"),
"only the one shared spawn may happen: {argv}"
);
}
#[tokio::test]
async fn a_cold_start_race_lost_to_our_own_project_attaches() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let project = tempfile::tempdir().expect("project");
let ours = project.path().canonicalize().expect("canonicalize");
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = sock_dir.path().join("tcode.sock");
let dir = tempfile::tempdir().expect("tempdir");
let argv_log = dir.path().join("argv");
let stub = stub_binary(
dir.path(),
"tcode-loses",
&format!(
"echo \"$@\" >> {argv}\ni=0\nwhile [ ! -S {sock} ] && [ $i -lt 500 ]; do \
sleep 0.01; i=$((i+1)); done\nexit 1",
argv = argv_log.display(),
sock = shared.display(),
),
);
bind_once_argv_has(
&argv_log,
"",
shared.clone(),
Some(binding_json(Some(&ours))),
);
let resolved = ensure_daemon_with(Some(&ours), &stub, &shared).await;
assert!(
matches!(&resolved, Ok(path) if *path == shared),
"a race lost to this project's own daemon must attach to it: {resolved:?}"
);
let argv = std::fs::read_to_string(&argv_log).unwrap_or_default();
assert!(
argv.lines().count() == 1 && !argv.contains("--project-socket"),
"no second daemon may start for this project: {argv}"
);
}
#[tokio::test]
async fn refuses_a_project_bound_client_against_a_projectless_daemon() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let project = tempfile::tempdir().expect("project");
let ours = project.path().canonicalize().expect("canonicalize");
{
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = sock_dir.path().join("tcode.sock");
stub_daemon_at(&own_socket(&shared, Some(&ours)), Some(binding_json(None)));
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let err = ensure_daemon_with(Some(&ours), &stub, &shared)
.await
.expect_err("a bound TUI must not attach to a projectless daemon");
let rendered = format!("{err:#}");
assert!(rendered.contains("<projectless>"), "{rendered}");
assert!(!marker.exists(), "must not spawn a competing daemon");
}
{
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = sock_dir.path().join("tcode.sock");
stub_daemon_at(&own_socket(&shared, None), Some(binding_json(Some(&ours))));
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let err = ensure_daemon_with(None, &stub, &shared)
.await
.expect_err("a projectless TUI must not inherit a daemon's project");
let rendered = format!("{err:#}");
assert!(rendered.contains(&ours.display().to_string()), "{rendered}");
assert!(rendered.contains("<projectless>"), "{rendered}");
assert!(!marker.exists(), "must not spawn a competing daemon");
}
}
#[tokio::test]
async fn refusal_against_a_projectless_daemon_names_the_projectless_flag() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let project = tempfile::tempdir().expect("project");
let ours = project.path().canonicalize().expect("canonicalize");
{
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = sock_dir.path().join("tcode.sock");
stub_daemon_at(&own_socket(&shared, Some(&ours)), Some(binding_json(None)));
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let err = ensure_daemon_with(Some(&ours), &stub, &shared)
.await
.expect_err("a repo-homed TUI must not attach to a projectless daemon");
let rendered = format!("{err:#}");
assert!(
rendered.contains("tcode tui --projectless"),
"the refusal must name the flag that matches a projectless daemon: {rendered}"
);
}
{
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = sock_dir.path().join("tcode.sock");
stub_daemon_at(&own_socket(&shared, None), Some(binding_json(Some(&ours))));
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let err = ensure_daemon_with(None, &stub, &shared)
.await
.expect_err("a projectless TUI must not inherit a daemon's project");
let rendered = format!("{err:#}");
assert!(
rendered.contains(&format!("tcode tui --project {}", ours.display())),
"the refusal must name the flag and the root: {rendered}"
);
}
}
#[tokio::test]
async fn refuses_a_daemon_that_cannot_report_its_binding() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let sock_dir = tempfile::tempdir().expect("socket dir");
let shared = sock_dir.path().join("tcode.sock");
stub_daemon_at(&own_socket(&shared, None), None);
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let err = ensure_daemon_with(None, &stub, &shared)
.await
.expect_err("an unverifiable daemon must not be attached to");
let rendered = format!("{err:#}");
assert!(
rendered.contains("does not report which project"),
"error must say the binding could not be confirmed: {rendered}"
);
assert!(!marker.exists(), "must not spawn a competing daemon");
}
#[test]
fn reported_binding_parses_every_health_shape() {
let project = tempfile::tempdir().expect("project");
let canonical = project.path().canonicalize().expect("canonicalize");
assert_eq!(
ReportedBinding::from_health(&serde_json::json!({"binding": binding_json(None)})),
ReportedBinding::Projectless
);
assert_eq!(
ReportedBinding::from_health(
&serde_json::json!({"binding": binding_json(Some(&canonical))})
),
ReportedBinding::Bound(canonical)
);
assert_eq!(
ReportedBinding::from_health(&serde_json::json!({"status": "ok"})),
ReportedBinding::Unreported
);
assert_eq!(
ReportedBinding::from_health(&serde_json::json!({"binding": "nonsense"})),
ReportedBinding::Unreported
);
}
#[test]
fn reported_binding_describes_each_state() {
assert_eq!(ReportedBinding::Projectless.describe(), "<projectless>");
assert_eq!(
ReportedBinding::Bound(PathBuf::from("/tmp/x")).describe(),
"/tmp/x"
);
assert!(
ReportedBinding::Unreported
.describe()
.contains("unreported")
);
}
#[tokio::test]
async fn spawns_a_daemon_when_none_is_running() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let project = tempfile::tempdir().expect("project");
let canonical = project.path().canonicalize().expect("canonicalize");
let sock_dir = tempfile::tempdir().expect("socket dir");
let socket = sock_dir.path().join("tcode.sock");
let dir = tempfile::tempdir().expect("tempdir");
let stub = SleepingStub::new(dir.path());
bind_socket_after_spawn(&stub, sock_dir.path(), binding_json(Some(&canonical)));
let resolved = ensure_daemon_with(Some(&canonical), &stub.path, &socket)
.await
.expect("must spawn a daemon");
assert_eq!(resolved, socket);
let argv = stub.argv().await;
assert!(argv.contains("serve"), "must spawn `serve`: {argv}");
assert!(
!argv.contains("--http") && !argv.contains("--port") && !argv.contains("--project-socket"),
"must spawn the socket-only daemon on the shared socket: {argv}"
);
assert!(
argv.contains("--project") && argv.contains(canonical.to_str().expect("utf8")),
"must forward --project to the daemon: {argv}"
);
}
#[tokio::test]
async fn spawns_projectless_when_the_tui_is_projectless() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let sock_dir = tempfile::tempdir().expect("socket dir");
let socket = sock_dir.path().join("tcode.sock");
let dir = tempfile::tempdir().expect("tempdir");
let stub = SleepingStub::new(dir.path());
bind_socket_after_spawn(&stub, sock_dir.path(), binding_json(None));
ensure_daemon_with(None, &stub.path, &socket)
.await
.expect("must spawn a daemon");
let argv = stub.argv().await;
assert!(
!argv.contains("--project"),
"a projectless TUI must not bind the daemon to a project: {argv}"
);
}
#[tokio::test]
async fn a_stalled_setup_still_reaches_the_spawn_branch() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let sock_dir = tempfile::tempdir().expect("socket dir");
let socket = sock_dir.path().join("tcode.sock");
let dir = tempfile::tempdir().expect("tempdir");
let stub = SleepingStub::new(dir.path());
bind_socket_after_spawn(&stub, sock_dir.path(), binding_json(None));
tokio::time::sleep(Duration::from_millis(600)).await;
assert!(
!socket_is_serving(&socket, Duration::from_millis(200)).await,
"nothing may answer {socket:?} before the stub has been spawned — a \
live socket here sends the call down the attach branch and the stub \
is never executed"
);
ensure_daemon_with(None, &stub.path, &socket)
.await
.expect("must spawn a daemon");
let argv = stub.argv().await;
assert!(
argv.contains("serve"),
"the spawn branch must have run the stub: {argv}"
);
}
#[tokio::test]
async fn daemon_autospawn_waits_on_socket_not_http() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let http = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/health"))
.respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
serde_json::json!({"server": "tcode", "status": "ok", "binding": binding_json(None)}),
))
.mount(&http)
.await;
let sock_dir = tempfile::tempdir().expect("socket dir");
let socket = sock_dir.path().join("tcode.sock");
let dir = tempfile::tempdir().expect("tempdir");
let stub = SleepingStub::new(dir.path());
let spawn_socket = socket.clone();
let spawn_stub = stub.path.clone();
let waiting =
tokio::spawn(async move { ensure_daemon_with(None, &spawn_stub, &spawn_socket).await });
tokio::time::sleep(Duration::from_millis(1200)).await;
assert!(
!waiting.is_finished(),
"a healthy HTTP listener must not satisfy the socket readiness gate"
);
stub_daemon_socket(sock_dir.path(), Some(binding_json(None)));
let resolved = tokio::time::timeout(Duration::from_secs(10), waiting)
.await
.expect("the wait must complete once the socket answers")
.expect("the wait task must not panic")
.expect("readiness must be reported");
assert_eq!(resolved, socket);
}
#[tokio::test]
async fn the_tui_never_signals_the_daemon_on_exit() {
let _lock = ENV_LOCK.lock().await;
let dir = tempfile::tempdir().expect("tempdir");
let stub = SleepingStub::new(dir.path());
let sock_dir = tempfile::tempdir().expect("socket dir");
let our_pid = {
let _env = EnvGuard::isolated();
let socket = sock_dir.path().join("tcode.sock");
bind_socket_after_spawn(&stub, sock_dir.path(), binding_json(None));
let resolved = ensure_daemon_with(None, &stub.path, &socket)
.await
.expect("must spawn a daemon");
assert_eq!(resolved, socket);
stub.pid().await
};
assert!(
is_alive(our_pid),
"a daemon the TUI spawned must OUTLIVE it (pid {our_pid} was killed)"
);
let _env = EnvGuard::isolated();
let foreign_sock_dir = tempfile::tempdir().expect("socket dir");
let foreign_socket = stub_daemon_socket(foreign_sock_dir.path(), Some(binding_json(None)));
let foreign_dir = tempfile::tempdir().expect("tempdir");
let foreign_stub = SleepingStub::new(foreign_dir.path());
let mut foreign = tokio::process::Command::new(&foreign_stub.path)
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn foreign daemon");
let foreign_pid = foreign.id().expect("foreign pid");
ensure_daemon_with(None, &foreign_stub.path, &foreign_socket)
.await
.expect("must attach");
assert!(
is_alive(foreign_pid),
"a pre-existing daemon must survive the TUI too (pid {foreign_pid})"
);
foreign.kill().await.expect("clean up foreign daemon");
}
#[tokio::test]
async fn reports_a_daemon_that_dies_on_startup() {
let _lock = ENV_LOCK.lock().await;
let _env = EnvGuard::isolated();
let stub = stable_stub("tcode-dies", "exit 3");
let sock_dir = tempfile::tempdir().expect("socket dir");
let socket = sock_dir.path().join("tcode.sock");
let started = std::time::Instant::now();
let err = ensure_daemon_with(None, &stub, &socket)
.await
.expect_err("a daemon that exits must surface an error");
assert!(
started.elapsed() < STARTUP_TIMEOUT,
"must fail fast rather than spin out the startup budget"
);
let rendered = format!("{err:#}");
assert!(
rendered.contains("exited during startup"),
"error must name the early exit: {rendered}"
);
}
#[tokio::test]
async fn the_spawned_daemon_leads_its_own_session() {
let stub = stable_stub("tcode-session", "exec sleep 300");
let mut child = spawn_daemon(&stub, None, false, None).expect("spawn the stub daemon");
let pid = child.id().expect("a live child has a pid") as libc::pid_t;
let sid = unsafe { libc::getsid(pid) };
child.start_kill().expect("signal the stub daemon");
child.wait().await.expect("reap the stub daemon");
assert_eq!(
sid, pid,
"the daemon `tcode tui` starts must lead its own session (#8783)"
);
}
fn fresh_body(tag: &str) -> String {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("clock after the epoch")
.as_nanos();
format!("# {tag} {} {nanos}\nexit 0", std::process::id())
}
#[test]
fn a_stable_stub_is_written_once_and_reused() {
use std::os::unix::fs::MetadataExt;
let first = stable_stub("tcode-stable", "exit 0");
let before = std::fs::metadata(&first).expect("stat the first stub");
let second = stable_stub("tcode-stable", "exit 0");
let after = std::fs::metadata(&second).expect("stat the second stub");
assert_eq!(first, second, "one body must map to one path");
assert!(first.starts_with(stable_stub_root()), "{first:?}");
assert_eq!(
before.ino(),
after.ino(),
"the second call rewrote the stub"
);
assert_eq!(
before.modified().expect("mtime"),
after.modified().expect("mtime"),
"the second call touched the stub"
);
}
#[test]
fn racing_stable_stub_writers_both_get_an_executable() {
use std::os::unix::fs::PermissionsExt;
for round in 0..3 {
let body = fresh_body(&format!("race-{round}"));
let barrier = std::sync::Barrier::new(2);
let paths: Vec<PathBuf> = std::thread::scope(|scope| {
let handles: Vec<_> = (0..2)
.map(|_| {
scope.spawn(|| {
barrier.wait();
stable_stub("tcode-race", &body)
})
})
.collect();
handles
.into_iter()
.map(|h| h.join().expect("writer thread"))
.collect()
});
let dir = paths[0].parent().expect("stub dir").to_path_buf();
let seen: Vec<_> = paths
.iter()
.map(|path| {
let mode = std::fs::metadata(path).expect("stat").permissions().mode();
(mode, std::fs::read_to_string(path).expect("read the stub"))
})
.collect();
let ran = (round == 0).then(|| {
std::process::Command::new(&paths[0])
.status()
.expect("run the stub")
});
let leftovers = std::fs::read_dir(&dir).expect("list stub dir").count();
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(paths[0], paths[1], "round {round}: one body, one path");
for (mode, text) in seen {
assert_eq!(mode & 0o111, 0o111, "round {round}: not executable");
assert_eq!(text, format!("#!/bin/sh\n{body}\n"), "round {round}");
}
if let Some(status) = ran {
assert!(status.success(), "round {round}: stub failed: {status}");
}
assert_eq!(leftovers, 1, "round {round}: a staging file was left");
}
}
#[test]
fn a_planted_stable_stub_is_refused_not_reused() {
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
for (case, wrong_body, mode) in [("body", true, 0o755), ("mode", false, 0o777)] {
let body = fresh_body(&format!("planted-{case}"));
let script = stable_stub_path("tcode-planted", &body);
let dir = script.parent().expect("stub dir").to_path_buf();
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(&dir)
.expect("create the planted dir");
let planted = if wrong_body { "exit 7" } else { body.as_str() };
std::fs::write(&script, format!("#!/bin/sh\n{planted}\n")).expect("plant");
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(mode))
.expect("chmod the planted stub");
let reused = std::panic::catch_unwind(|| stable_stub("tcode-planted", &body));
let _ = std::fs::remove_dir_all(&dir);
assert!(reused.is_err(), "{case}: a planted stub was reused");
}
}
#[tokio::test]
async fn a_linked_marker_stub_marks_its_own_dir() {
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().join("spawned");
let stub = marker_stub(dir.path(), &marker);
let mut child = spawn_daemon(&stub, None, false, None).expect("spawn the marker stub");
let mut seen = false;
for _ in 0..200 {
if marker.exists() {
seen = true;
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
child.start_kill().expect("signal the marker stub");
child.wait().await.expect("reap the marker stub");
assert!(seen, "a run marker stub must touch {marker:?}");
}