use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::path::Path;
use std::time::Duration;
use super::{Definitions, Impact, MeasureReply, Neighbors};
use crate::config::HankConfig;
use crate::graph::Dir;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reachability {
Up,
Down(String),
}
impl Reachability {
#[must_use]
pub fn is_up(&self) -> bool {
matches!(self, Reachability::Up)
}
#[must_use]
pub fn down_reason(&self) -> Option<&str> {
match self {
Reachability::Up => None,
Reachability::Down(why) => Some(why),
}
}
}
#[must_use]
pub fn probe(host: &str, port: u16, timeout: Duration) -> Reachability {
let addr = format!("{host}:{port}");
let Ok(mut addrs) = addr.to_socket_addrs() else {
return Reachability::Down(format!("cannot resolve {addr}"));
};
let Some(sockaddr) = addrs.next() else {
return Reachability::Down(format!("no address for {addr}"));
};
let mut stream = match TcpStream::connect_timeout(&sockaddr, timeout) {
Ok(s) => s,
Err(e) => return Reachability::Down(format!("no daemon at {addr} ({e})")),
};
let _ = stream.set_read_timeout(Some(timeout));
let _ = stream.set_write_timeout(Some(timeout));
let req = format!("GET /health HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
if let Err(e) = stream.write_all(req.as_bytes()) {
return Reachability::Down(format!("write to {addr} failed ({e})"));
}
let mut buf = Vec::with_capacity(64);
let mut byte = [0u8; 1];
loop {
match stream.read(&mut byte) {
Ok(0) => break,
Ok(_) => {
if byte[0] == b'\n' || buf.len() >= 64 {
break;
}
buf.push(byte[0]);
}
Err(e) => return Reachability::Down(format!("read from {addr} failed ({e})")),
}
}
let line = String::from_utf8_lossy(&buf);
match line.split_whitespace().nth(1) {
Some(code) if code.starts_with('2') => Reachability::Up,
Some(code) => Reachability::Down(format!("daemon at {addr} returned HTTP {code}")),
None => Reachability::Down(format!("daemon at {addr} sent no status line")),
}
}
pub fn fetch_measure(
host: &str,
port: u16,
file: &str,
rel: &str,
anchors: &[String],
max_hops: u32,
timeout: Duration,
) -> Result<MeasureReply, String> {
let addr = format!("{host}:{port}");
let body = serde_json::json!({
"file": file,
"rel": rel,
"anchors": anchors,
"max_hops": max_hops,
})
.to_string();
let raw = http_post(host, port, "/measure", &body, timeout)?;
serde_json::from_str::<MeasureReply>(&raw)
.map_err(|e| format!("daemon at {addr} sent an unparseable measure reply ({e})"))
}
fn http_post(
host: &str,
port: u16,
path: &str,
body: &str,
timeout: Duration,
) -> Result<String, String> {
let addr = format!("{host}:{port}");
let Ok(mut addrs) = addr.to_socket_addrs() else {
return Err(format!("cannot resolve {addr}"));
};
let Some(sockaddr) = addrs.next() else {
return Err(format!("no address for {addr}"));
};
let mut stream = TcpStream::connect_timeout(&sockaddr, timeout)
.map_err(|e| format!("no daemon at {addr} ({e})"))?;
let _ = stream.set_read_timeout(Some(timeout));
let _ = stream.set_write_timeout(Some(timeout));
let req = format!(
"POST {path} HTTP/1.1\r\nHost: {host}\r\nContent-Type: application/json\r\n\
Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
stream
.write_all(req.as_bytes())
.map_err(|e| format!("write to {addr} failed ({e})"))?;
let mut raw = String::new();
stream
.read_to_string(&mut raw)
.map_err(|e| format!("read from {addr} failed ({e})"))?;
let status = raw
.split_whitespace()
.nth(1)
.ok_or_else(|| format!("daemon at {addr} sent no status line"))?;
if !status.starts_with('2') {
return Err(format!("daemon at {addr} returned HTTP {status}"));
}
raw.split("\r\n\r\n")
.nth(1)
.map(str::to_string)
.ok_or_else(|| format!("daemon at {addr} sent no body"))
}
fn http_get(host: &str, port: u16, path: &str, timeout: Duration) -> Result<String, String> {
let addr = format!("{host}:{port}");
let Ok(mut addrs) = addr.to_socket_addrs() else {
return Err(format!("cannot resolve {addr}"));
};
let Some(sockaddr) = addrs.next() else {
return Err(format!("no address for {addr}"));
};
let mut stream = TcpStream::connect_timeout(&sockaddr, timeout)
.map_err(|e| format!("no daemon at {addr} ({e})"))?;
let _ = stream.set_read_timeout(Some(timeout));
let _ = stream.set_write_timeout(Some(timeout));
let req = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
stream
.write_all(req.as_bytes())
.map_err(|e| format!("write to {addr} failed ({e})"))?;
let mut raw = String::new();
stream
.read_to_string(&mut raw)
.map_err(|e| format!("read from {addr} failed ({e})"))?;
let status = raw
.split_whitespace()
.nth(1)
.ok_or_else(|| format!("daemon at {addr} sent no status line"))?;
if !status.starts_with('2') {
return Err(format!("daemon at {addr} returned HTTP {status}"));
}
raw.split("\r\n\r\n")
.nth(1)
.map(str::to_string)
.ok_or_else(|| format!("daemon at {addr} sent no body"))
}
fn urlencode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(b as char);
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
pub fn fetch_status_json(
host: &str,
port: u16,
timeout: Duration,
) -> Result<serde_json::Value, String> {
let body = http_get(host, port, "/status", timeout)?;
serde_json::from_str(&body)
.map_err(|e| format!("daemon at {host}:{port} sent an unparseable status ({e})"))
}
pub fn fetch_root(host: &str, port: u16, timeout: Duration) -> Result<String, String> {
let body = http_get(host, port, "/status", timeout)?;
let status: serde_json::Value = serde_json::from_str(&body)
.map_err(|e| format!("daemon at {host}:{port} sent an unparseable status ({e})"))?;
status
.get("root")
.and_then(serde_json::Value::as_str)
.map(str::to_string)
.ok_or_else(|| format!("daemon at {host}:{port} status reports no root"))
}
pub fn fetch_neighbors(
host: &str,
port: u16,
symbol: &str,
dir: Dir,
timeout: Duration,
) -> Result<Neighbors, String> {
let endpoint = match dir {
Dir::Callers => "callers",
Dir::Callees => "callees",
};
let body = http_get(
host,
port,
&format!("/{endpoint}?symbol={}", urlencode(symbol)),
timeout,
)?;
serde_json::from_str(&body)
.map_err(|e| format!("daemon at {host}:{port} sent an unparseable {endpoint} reply ({e})"))
}
pub fn fetch_impact(
host: &str,
port: u16,
symbol: &str,
hops: u32,
timeout: Duration,
) -> Result<Impact, String> {
let body = http_get(
host,
port,
&format!("/impact?symbol={}&hops={hops}", urlencode(symbol)),
timeout,
)?;
serde_json::from_str(&body)
.map_err(|e| format!("daemon at {host}:{port} sent an unparseable impact reply ({e})"))
}
pub fn expected_same_root_daemon(
config: &HankConfig,
root: &Path,
timeout: Duration,
) -> Option<Result<(String, u16), String>> {
if !config.serve.use_daemon {
return None;
}
let host = config.serve.bind_address.clone();
let port = config.serve.mcp_http_port;
let served = match fetch_root(&host, port, timeout) {
Ok(served) => served,
Err(reason) => return Some(Err(reason)),
};
let same = match (Path::new(&served).canonicalize(), root.canonicalize()) {
(Ok(theirs), Ok(ours)) => theirs == ours,
_ => false,
};
if !same {
return Some(Err(format!(
"daemon at {host}:{port} serves {served}, not {}",
root.display()
)));
}
Some(Ok((host, port)))
}
pub fn fetch_edit(
host: &str,
port: u16,
tenant: &str,
rel: &str,
timeout: Duration,
) -> Result<super::EditReply, String> {
let addr = format!("{host}:{port}");
let body = serde_json::json!({ "tenant": tenant, "rel": rel }).to_string();
let raw = http_post(host, port, "/edit", &body, timeout)?;
serde_json::from_str(&raw)
.map_err(|e| format!("daemon at {addr} sent an unparseable edit reply ({e})"))
}
pub fn fetch_references(
host: &str,
port: u16,
symbol: &str,
timeout: Duration,
) -> Result<Definitions, String> {
let body = http_get(
host,
port,
&format!("/references?symbol={}", urlencode(symbol)),
timeout,
)?;
serde_json::from_str(&body)
.map_err(|e| format!("daemon at {host}:{port} sent an unparseable references reply ({e})"))
}
#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
use super::*;
#[test]
fn a_closed_port_is_DOWN_with_a_reason_not_a_panic() {
let r = probe("127.0.0.1", 1, Duration::from_millis(200));
assert!(!r.is_up());
assert!(
r.down_reason().is_some(),
"Down must carry a reason for the notice"
);
}
#[test]
fn an_unroutable_host_is_DOWN_not_UP() {
let r = probe(
"no.such.host.hank.invalid",
3040,
Duration::from_millis(200),
);
assert!(!r.is_up());
}
#[test]
fn urlencode_passes_identifiers_and_encodes_request_line_metacharacters() {
assert_eq!(urlencode("authenticate_v2"), "authenticate_v2");
assert_eq!(urlencode("a&b ?c"), "a%26b%20%3Fc");
}
#[test]
fn fetch_neighbors_and_impact_on_a_closed_port_are_Err_never_empty() {
let n = fetch_neighbors(
"127.0.0.1",
1,
"leaf",
Dir::Callers,
Duration::from_millis(200),
);
assert!(n.is_err());
let i = fetch_impact("127.0.0.1", 1, "leaf", 5, Duration::from_millis(200));
assert!(i.is_err());
let r = fetch_root("127.0.0.1", 1, Duration::from_millis(200));
assert!(r.is_err());
}
#[test]
fn down_and_up_are_distinct_and_reason_only_on_down() {
assert!(Reachability::Up.is_up());
assert_eq!(Reachability::Up.down_reason(), None);
let d = Reachability::Down("no daemon".into());
assert!(!d.is_up());
assert_eq!(d.down_reason(), Some("no daemon"));
}
}