use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use anyhow::{Context, Result, anyhow};
use tokio::process::{Child, Command};
use trusty_code::serve::DEFAULT_HTTP_PORT;
use trusty_code::tui_client::discovery::{
DAEMON_URL_ENV, Lookup, ReportedBinding, Source, lookup_daemon,
};
use trusty_common::daemon_guard::{DaemonGuardConfig, spin_until_ready};
const STARTUP_TIMEOUT: Duration = Duration::from_secs(20);
const DAEMON_LOG_FILENAME: &str = "tui-spawned-daemon.log";
pub async fn ensure_daemon(client: &reqwest::Client, project: Option<&Path>) -> Result<String> {
let tcode_exe = super::tcode_exe::resolve()?;
let health_url = format!("http://127.0.0.1:{DEFAULT_HTTP_PORT}");
ensure_daemon_with(client, project, &tcode_exe, &health_url).await
}
async fn ensure_daemon_with(
client: &reqwest::Client,
project: Option<&Path>,
tcode_exe: &Path,
health_base_url: &str,
) -> Result<String> {
match lookup_daemon(client).await {
Lookup::Live { url, binding } => check_binding(&url, &binding, project).map(|()| url),
Lookup::Dead {
url,
source: Source::Env,
} => Err(explicit_url_unreachable(&url)),
Lookup::Dead {
source: Source::File,
..
}
| Lookup::Absent => spawn_and_wait(project, tcode_exe, health_base_url).await,
}
}
fn check_binding(url: &str, reported: &ReportedBinding, wanted: Option<&Path>) -> Result<()> {
let wanted_label = wanted
.map(|p| p.display().to_string())
.unwrap_or_else(|| "<projectless>".to_string());
match (reported, wanted) {
(ReportedBinding::Projectless, None) => Ok(()),
(ReportedBinding::Bound(root), Some(wanted)) if root == wanted => Ok(()),
(ReportedBinding::Unreported, _) => Err(anyhow!(
"the tcode daemon at {url} does not report which project it serves, \
so `tcode tui` cannot confirm it is bound to {wanted_label} — and \
attaching to the wrong project would run every session against the \
wrong repository. That daemon predates the binding check (#4512): \
stop it and let `tcode tui` start a current one, or restart it from \
this build of `tcode serve --http`."
)),
_ => Err(anyhow!(
"the tcode daemon at {url} serves a different project than this TUI: \
daemon = {daemon}, requested = {wanted_label}. `tcode tui` will not \
attach to it (every session would run against the wrong project) and \
will not start a competing daemon on a port that is already in use. \
Either relaunch this TUI against {daemon}, or stop that daemon and \
let this one start its own, or point `{DAEMON_URL_ENV}` at a daemon \
serving {wanted_label}.",
daemon = reported.describe(),
)),
}
}
fn explicit_url_unreachable(url: &str) -> anyhow::Error {
anyhow!(
"{DAEMON_URL_ENV} is set to {url} but no daemon is responding there. \
`tcode tui` will not start one for you while {DAEMON_URL_ENV} names an \
address explicitly — spawning at a different address would ignore that \
setting. Start `tcode serve --http` at {url}, or unset {DAEMON_URL_ENV} \
and let `tcode tui` start a daemon itself."
)
}
async fn spawn_and_wait(
project: Option<&Path>,
tcode_exe: &Path,
health_base_url: &str,
) -> Result<String> {
let log_path = daemon_log_path();
let mut child = spawn_daemon(tcode_exe, project, log_path.as_deref())?;
let config = DaemonGuardConfig {
startup_timeout: STARTUP_TIMEOUT,
..DaemonGuardConfig::new(
format!("{health_base_url}/health"),
"the tcode daemon",
log_hint(log_path.as_deref()),
)
};
let outcome = tokio::select! {
ready = spin_until_ready(&config) => Outcome::Ready(ready),
exit = child.wait() => Outcome::Exited(exit.map(|s| s.to_string())),
};
match outcome {
Outcome::Ready(Ok(())) => {
if matches!(child.try_wait(), Ok(Some(_))) {
return Err(exited_early(
"it exited during startup",
log_path.as_deref(),
));
}
Ok(health_base_url.to_string())
}
Outcome::Ready(Err(e)) => Err(e),
Outcome::Exited(status) => {
let detail = match status {
Ok(s) => format!("it exited during startup ({s})"),
Err(e) => format!("its exit status could not be read ({e})"),
};
Err(exited_early(&detail, log_path.as_deref()))
}
}
}
enum Outcome {
Ready(Result<()>),
Exited(std::io::Result<String>),
}
fn spawn_daemon(
tcode_exe: &Path,
project: Option<&Path>,
log_path: Option<&Path>,
) -> Result<Child> {
let mut cmd = Command::new(tcode_exe);
cmd.arg("serve").arg("--http");
if let Some(project) = project {
cmd.arg("--project").arg(project);
}
cmd.stdin(Stdio::null());
match log_path.and_then(open_log) {
Some((out, err)) => {
cmd.stdout(out).stderr(err);
}
None => {
cmd.stdout(Stdio::null()).stderr(Stdio::null());
}
}
cmd.spawn().with_context(|| {
format!(
"tcode tui: could not start a daemon with `{} serve --http`",
tcode_exe.display()
)
})
}
fn open_log(path: &Path) -> Option<(Stdio, Stdio)> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).ok()?;
}
let open = || {
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.ok()
};
Some((Stdio::from(open()?), Stdio::from(open()?)))
}
fn daemon_log_path() -> Option<PathBuf> {
trusty_common::resolve_data_dir("trusty-code")
.ok()
.map(|dir| dir.join(DAEMON_LOG_FILENAME))
}
fn log_hint(log_path: Option<&Path>) -> String {
match log_path {
Some(path) => format!("see {} for the daemon's own output", path.display()),
None => "run `tcode serve --http` by hand to see why".to_string(),
}
}
fn exited_early(detail: &str, log_path: Option<&Path>) -> anyhow::Error {
anyhow!(
"tcode tui: started a daemon but {detail} — {}. A daemon already \
holding port {DEFAULT_HTTP_PORT} is the usual cause.",
log_hint(log_path)
)
}
#[cfg(test)]
#[path = "daemon_autospawn_tests.rs"]
mod daemon_autospawn_tests;