use std::time::Duration;
pub fn daemon_base_url() -> String {
if let Some(addr) = read_http_addr_file() {
return format!("http://{addr}");
}
let port = daemon_port_path()
.and_then(|p| std::fs::read_to_string(p).ok())
.and_then(|s| s.trim().parse::<u16>().ok())
.unwrap_or(trusty_search::service::DEFAULT_PORT);
format!("http://127.0.0.1:{port}")
}
pub fn read_http_addr_file() -> Option<String> {
let path = http_addr_path()?;
let raw = std::fs::read_to_string(&path).ok()?;
let trimmed = raw.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
pub fn http_addr_path() -> Option<std::path::PathBuf> {
dirs::home_dir().map(|h| h.join(".trusty-search").join("http_addr"))
}
pub fn daemon_port_path() -> Option<std::path::PathBuf> {
dirs::data_local_dir().map(|d| d.join("trusty-search").join("daemon.port"))
}
pub async fn port_reachable(host: &str, port: u16) -> bool {
let addr = format!("{}:{}", host, port);
tokio::time::timeout(
Duration::from_millis(500),
tokio::net::TcpStream::connect(&addr),
)
.await
.ok()
.and_then(|r| r.ok())
.is_some()
}