lean_ctx/lsp/
port_discovery.rs1use std::time::Duration;
9
10use serde::Deserialize;
11
12#[derive(Debug, Clone, Deserialize)]
14pub struct PortFile {
15 pub port: u16,
16 pub token: String,
17 pub pid: u32,
18 #[serde(default)]
19 pub project_root: String,
20 #[serde(default)]
21 pub ide_version: String,
22}
23
24pub fn project_hash(project_root: &str) -> String {
26 use std::fmt::Write as _;
27
28 use sha2::{Digest, Sha256};
29 let canonical = std::fs::canonicalize(project_root).map_or_else(
30 |_| project_root.to_string(),
31 |p| p.to_string_lossy().to_string(),
32 );
33 let digest = Sha256::digest(canonical.as_bytes());
34 let mut hex = String::with_capacity(16);
35 for b in digest.iter().take(8) {
36 let _ = write!(hex, "{b:02x}");
37 }
38 hex
39}
40
41pub fn port_file_path(project_root: &str) -> Option<std::path::PathBuf> {
45 let dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
46 Some(dir.join(format!("jetbrains-{}.port", project_hash(project_root))))
47}
48
49pub fn read_port_file(project_root: &str) -> Option<PortFile> {
51 let path = port_file_path(project_root)?;
52 let text = std::fs::read_to_string(path).ok()?;
53 serde_json::from_str(&text).ok()
54}
55
56pub fn pid_alive(pid: u32) -> bool {
59 #[cfg(target_os = "linux")]
60 {
61 std::path::Path::new(&format!("/proc/{pid}")).exists()
62 }
63 #[cfg(not(target_os = "linux"))]
64 {
65 let _ = pid;
66 true
67 }
68}
69
70pub fn health_ok(pf: &PortFile) -> bool {
73 let url = format!("http://127.0.0.1:{}/health", pf.port);
74 ureq::get(&url)
75 .config()
76 .timeout_global(Some(Duration::from_millis(300)))
77 .build()
78 .header("X-LeanCtx-Token", &pf.token)
79 .call()
80 .is_ok()
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86
87 #[test]
88 fn project_hash_is_stable_and_16_hex() {
89 let h1 = project_hash("/some/project");
90 let h2 = project_hash("/some/project");
91 assert_eq!(h1, h2, "hash must be deterministic");
92 assert_eq!(h1.len(), 16, "expected 16 hex chars (8 bytes)");
93 assert!(h1.chars().all(|c| c.is_ascii_hexdigit()));
94 }
95
96 #[test]
97 fn port_file_absent_for_unlikely_root() {
98 assert!(read_port_file("/nonexistent/lean-ctx/project/xyz").is_none());
100 }
101
102 #[test]
103 fn project_hash_matches_known_vector() {
104 assert_eq!(project_hash("/some/project"), "a0317725f24b01df");
107 }
108
109 #[test]
110 fn port_file_path_honors_data_dir_env() {
111 let _lock = crate::core::data_dir::test_env_lock();
112 let dir = std::env::temp_dir().join("lc_jb_portfile_env");
113 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
114 let p = port_file_path("/some/project").unwrap();
115 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
116 assert_eq!(p, dir.join("jetbrains-a0317725f24b01df.port"));
117 }
118}