use std::path::PathBuf;
use std::time::Duration;
use crate::binding::ProjectBinding;
pub const DAEMON_URL_ENV: &str = "TCODE_DAEMON_URL";
const PING_TIMEOUT: Duration = Duration::from_secs(2);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
Env,
File,
}
impl Source {
pub fn as_str(self) -> &'static str {
match self {
Source::Env => "TCODE_DAEMON_URL",
Source::File => "discovery file",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReportedBinding {
Projectless,
Bound(PathBuf),
Unreported,
}
impl ReportedBinding {
pub fn from_health(health: &serde_json::Value) -> Self {
let Some(raw) = health.get("binding") else {
return Self::Unreported;
};
match serde_json::from_value::<ProjectBinding>(raw.clone()) {
Ok(binding) => match binding.root() {
Some(root) => Self::Bound(root.to_path_buf()),
None => Self::Projectless,
},
Err(_) => Self::Unreported,
}
}
pub fn describe(&self) -> String {
match self {
Self::Projectless => "<projectless>".to_string(),
Self::Bound(root) => root.display().to_string(),
Self::Unreported => "<unreported — daemon predates #4512>".to_string(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Lookup {
Live {
url: String,
binding: ReportedBinding,
},
Dead { url: String, source: Source },
Absent,
}
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum DiscoveryError {
#[error(
"no tcode daemon found — start one with `tcode serve --http`, or point \
`tcode tui` at a running instance with `{DAEMON_URL_ENV}=http://host:port`"
)]
NotFound,
#[error(
"found a tcode daemon reference at {url} (from {found_via}) but it is not responding \
— is it still running? Start one with `tcode serve --http`, or update {DAEMON_URL_ENV} \
to point at a live daemon"
)]
NotAlive {
url: String,
found_via: &'static str,
},
}
pub async fn lookup_daemon(client: &reqwest::Client) -> Lookup {
let Some((url, source)) = candidate_url() else {
return Lookup::Absent;
};
match probe_health(client, &url).await {
Some(health) => Lookup::Live {
url,
binding: ReportedBinding::from_health(&health),
},
None => Lookup::Dead { url, source },
}
}
pub async fn discover_daemon_url(client: &reqwest::Client) -> Result<String, DiscoveryError> {
collapse(lookup_daemon(client).await)
}
fn collapse(lookup: Lookup) -> Result<String, DiscoveryError> {
match lookup {
Lookup::Live { url, .. } => Ok(url),
Lookup::Dead { url, source } => Err(DiscoveryError::NotAlive {
url,
found_via: source.as_str(),
}),
Lookup::Absent => Err(DiscoveryError::NotFound),
}
}
fn candidate_url() -> Option<(String, Source)> {
if let Ok(raw) = std::env::var(DAEMON_URL_ENV) {
let trimmed = raw.trim();
if !trimmed.is_empty() {
return Some((trimmed.trim_end_matches('/').to_string(), Source::Env));
}
}
let path = crate::serve::discovery::http_addr_path()?;
let addr = crate::serve::discovery::read_http_addr_file(&path)?;
Some((format!("http://{addr}"), Source::File))
}
async fn probe_health(client: &reqwest::Client, base_url: &str) -> Option<serde_json::Value> {
let url = format!("{base_url}/health");
let resp = client.get(&url).timeout(PING_TIMEOUT).send().await.ok()?;
if !resp.status().is_success() {
return None;
}
Some(resp.json().await.unwrap_or(serde_json::Value::Null))
}
#[cfg(test)]
mod discovery_tests {
use super::*;
static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
#[tokio::test]
async fn env_var_wins_over_file() {
let _guard = ENV_LOCK.lock().await;
unsafe {
std::env::set_var(DAEMON_URL_ENV, "http://127.0.0.1:9999");
}
let (url, source) = candidate_url().expect("candidate");
unsafe {
std::env::remove_var(DAEMON_URL_ENV);
}
assert_eq!(url, "http://127.0.0.1:9999");
assert_eq!(source, Source::Env);
}
#[tokio::test]
async fn env_var_trailing_slash_is_stripped() {
let _guard = ENV_LOCK.lock().await;
unsafe {
std::env::set_var(DAEMON_URL_ENV, "http://127.0.0.1:9999/");
}
let (url, _source) = candidate_url().expect("candidate");
unsafe {
std::env::remove_var(DAEMON_URL_ENV);
}
assert_eq!(url, "http://127.0.0.1:9999");
}
#[tokio::test]
async fn blank_env_var_is_ignored() {
let _guard = ENV_LOCK.lock().await;
unsafe {
std::env::set_var(DAEMON_URL_ENV, " ");
}
let result = candidate_url();
unsafe {
std::env::remove_var(DAEMON_URL_ENV);
}
if let Some((_, source)) = result {
assert_ne!(source, Source::Env);
}
}
#[test]
fn not_found_message_is_actionable() {
let msg = DiscoveryError::NotFound.to_string();
assert!(msg.contains("tcode serve --http"));
assert!(msg.contains(DAEMON_URL_ENV));
}
#[test]
fn lookup_collapses_into_discovery_errors() {
assert_eq!(
collapse(Lookup::Live {
url: "http://127.0.0.1:7882".to_string(),
binding: ReportedBinding::Projectless,
}),
Ok("http://127.0.0.1:7882".to_string())
);
assert_eq!(
collapse(Lookup::Dead {
url: "http://127.0.0.1:7882".to_string(),
source: Source::Env,
}),
Err(DiscoveryError::NotAlive {
url: "http://127.0.0.1:7882".to_string(),
found_via: "TCODE_DAEMON_URL",
})
);
assert_eq!(collapse(Lookup::Absent), Err(DiscoveryError::NotFound));
}
#[test]
fn reported_binding_parses_every_health_shape() {
use serde_json::json;
let bound = json!({
"server": "tcode",
"binding": {"state": crate::binding::STATE_GIT_REPO, "root": "/tmp/proj"},
});
assert_eq!(
ReportedBinding::from_health(&bound),
ReportedBinding::Bound(PathBuf::from("/tmp/proj"))
);
let projectless = json!({
"binding": {"state": crate::binding::STATE_PROJECTLESS, "root": null},
});
assert_eq!(
ReportedBinding::from_health(&projectless),
ReportedBinding::Projectless
);
let old = json!({"server": "tcode", "version": "0.2.0", "status": "ok"});
assert_eq!(
ReportedBinding::from_health(&old),
ReportedBinding::Unreported,
"a daemon that reports nothing must never read as projectless"
);
let malformed = json!({"binding": {"state": "who knows"}});
assert_eq!(
ReportedBinding::from_health(&malformed),
ReportedBinding::Unreported
);
assert_eq!(
ReportedBinding::from_health(&serde_json::Value::Null),
ReportedBinding::Unreported
);
}
#[test]
fn reported_binding_describes_each_state() {
assert_eq!(ReportedBinding::Projectless.describe(), "<projectless>");
assert_eq!(
ReportedBinding::Bound(PathBuf::from("/tmp/proj")).describe(),
"/tmp/proj"
);
assert!(
ReportedBinding::Unreported.describe().contains("4512"),
"an unverifiable daemon must say why it cannot be checked"
);
}
#[test]
fn not_alive_message_names_url_and_source() {
let err = DiscoveryError::NotAlive {
url: "http://127.0.0.1:7882".to_string(),
found_via: Source::File.as_str(),
};
let msg = err.to_string();
assert!(msg.contains("http://127.0.0.1:7882"));
assert!(msg.contains("discovery file"));
}
}