Skip to main content

blyte_cli/
surface_dir.rs

1use std::io::{ErrorKind, Read, Write};
2use std::net::{SocketAddr, TcpStream};
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::time::Duration;
6
7use blyte_agent::sandbox::validate_surface_id;
8use serde::{Deserialize, Serialize};
9
10const PROBE_TIMEOUT: Duration = Duration::from_millis(300);
11const PROBE_RETRY_TIMEOUT: Duration = Duration::from_secs(2);
12
13static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Liveness {
17    Running,
18    NotRunning,
19    Unknown,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct SurfaceRecord {
24    pub id: String,
25    pub name: String,
26    pub pid: u32,
27    pub port: u16,
28    pub session_id: String,
29    pub started_at: u64,
30}
31
32pub fn new_surface_id() -> Result<String, String> {
33    let mut bytes = [0u8; 8];
34    let mut file = std::fs::File::open("/dev/urandom")
35        .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
36    file.read_exact(&mut bytes)
37        .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
38    const HEX: &[u8; 16] = b"0123456789abcdef";
39    let mut out = String::with_capacity(17);
40    out.push('s');
41    for byte in bytes {
42        out.push(HEX[(byte >> 4) as usize] as char);
43        out.push(HEX[(byte & 0x0f) as usize] as char);
44    }
45    Ok(out)
46}
47
48pub fn validate_surface_name(name: &str) -> Result<(), String> {
49    let bytes = name.as_bytes();
50    let valid = !bytes.is_empty()
51        && bytes.len() <= 64
52        && bytes[0].is_ascii_alphanumeric()
53        && bytes
54            .iter()
55            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
56    if valid {
57        Ok(())
58    } else {
59        Err(format!(
60            "invalid surface name: {name} (use letters, digits, '.', '_' and '-', starting with a letter or digit)"
61        ))
62    }
63}
64
65pub fn surfaces_dir(main_checkout: &Path) -> PathBuf {
66    main_checkout.join(".wt").join("surfaces")
67}
68
69pub fn surface_dir(main_checkout: &Path, id: &str) -> PathBuf {
70    surfaces_dir(main_checkout).join(id)
71}
72
73pub fn record_path(main_checkout: &Path, id: &str) -> PathBuf {
74    surface_dir(main_checkout, id).join("surface.json")
75}
76
77pub fn entries_path(main_checkout: &Path, id: &str) -> PathBuf {
78    surface_dir(main_checkout, id).join("entries.jsonl")
79}
80
81pub fn write_record(main_checkout: &Path, record: &SurfaceRecord) -> Result<(), String> {
82    validate_surface_id(&record.id)?;
83    validate_surface_name(&record.name)?;
84    let dir = surface_dir(main_checkout, &record.id);
85    std::fs::create_dir_all(&dir)
86        .map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
87    let mut json = serde_json::to_string_pretty(record)
88        .map_err(|e| format!("failed to serialize surface record {}: {e}", record.id))?;
89    json.push('\n');
90    let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
91    let tmp = dir.join(format!("surface.json.tmp.{}.{seq}", std::process::id()));
92    let dest = record_path(main_checkout, &record.id);
93    if let Err(e) = std::fs::write(&tmp, json.as_bytes()) {
94        let _ = std::fs::remove_file(&tmp);
95        return Err(format!("failed to write {}: {e}", tmp.display()));
96    }
97    if let Err(e) = std::fs::rename(&tmp, &dest) {
98        let _ = std::fs::remove_file(&tmp);
99        return Err(format!(
100            "failed to rename {} to {}: {e}",
101            tmp.display(),
102            dest.display()
103        ));
104    }
105    Ok(())
106}
107
108pub fn read_record(main_checkout: &Path, id: &str) -> Result<SurfaceRecord, String> {
109    validate_surface_id(id)?;
110    let path = record_path(main_checkout, id);
111    let text = std::fs::read_to_string(&path)
112        .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
113    let record: SurfaceRecord = serde_json::from_str(&text)
114        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
115    if record.id != id {
116        return Err(format!(
117            "surface record {} has id {}, expected {id}",
118            path.display(),
119            record.id
120        ));
121    }
122    if let Err(e) = validate_surface_name(&record.name) {
123        return Err(format!("surface record {} has {e}", path.display()));
124    }
125    Ok(record)
126}
127
128pub fn list_records(main_checkout: &Path) -> Result<Vec<SurfaceRecord>, String> {
129    let root = surfaces_dir(main_checkout);
130    let entries = match std::fs::read_dir(&root) {
131        Ok(entries) => entries,
132        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
133        Err(e) => return Err(format!("failed to read {}: {e}", root.display())),
134    };
135    let mut records = Vec::new();
136    for entry in entries {
137        let entry = entry.map_err(|e| format!("failed to read {}: {e}", root.display()))?;
138        let path = entry.path();
139        let file_type = entry
140            .file_type()
141            .map_err(|e| format!("failed to inspect {}: {e}", path.display()))?;
142        if !file_type.is_dir() {
143            continue;
144        }
145        let name_os = entry.file_name();
146        let Some(id) = name_os.to_str() else {
147            return Err(format!("invalid surface directory: {}", path.display()));
148        };
149        if let Err(e) = validate_surface_id(id) {
150            return Err(format!("invalid surface directory {}: {e}", path.display()));
151        }
152        let record = read_record(main_checkout, id)?;
153        records.push(record);
154    }
155    records.sort_by(|a, b| {
156        a.started_at
157            .cmp(&b.started_at)
158            .then_with(|| a.id.cmp(&b.id))
159    });
160    Ok(records)
161}
162
163fn pid_exists(pid: u32) -> bool {
164    let Ok(raw_pid) = libc::pid_t::try_from(pid) else {
165        return false;
166    };
167    if raw_pid <= 0 {
168        return false;
169    }
170    let ret = unsafe { libc::kill(raw_pid, 0) };
171    if ret == 0 {
172        return true;
173    }
174    !matches!(
175        std::io::Error::last_os_error().raw_os_error(),
176        Some(libc::ESRCH)
177    )
178}
179
180fn probe_once(port: u16, id: &str, timeout: Duration) -> Liveness {
181    let addr = SocketAddr::from(([127, 0, 0, 1], port));
182    let mut stream = match TcpStream::connect_timeout(&addr, timeout) {
183        Ok(s) => s,
184        Err(e) if e.kind() == ErrorKind::ConnectionRefused => return Liveness::NotRunning,
185        Err(_) => return Liveness::Unknown,
186    };
187    if stream.set_read_timeout(Some(timeout)).is_err() {
188        return Liveness::Unknown;
189    }
190    if stream.set_write_timeout(Some(timeout)).is_err() {
191        return Liveness::Unknown;
192    }
193    let req =
194        format!("GET /api/health HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
195    if stream.write_all(req.as_bytes()).is_err() {
196        return Liveness::Unknown;
197    }
198    let mut raw = Vec::new();
199    if stream.read_to_end(&mut raw).is_err() {
200        return Liveness::Unknown;
201    }
202    let Ok(text) = std::str::from_utf8(&raw) else {
203        return Liveness::NotRunning;
204    };
205    let Some((head, body)) = text.split_once("\r\n\r\n") else {
206        return Liveness::NotRunning;
207    };
208    let status_line = head.lines().next().unwrap_or("");
209    if !(status_line.starts_with("HTTP/1.1 200") || status_line.starts_with("HTTP/1.0 200")) {
210        return Liveness::NotRunning;
211    }
212    let Ok(val) = serde_json::from_str::<serde_json::Value>(body) else {
213        return Liveness::NotRunning;
214    };
215    if val.get("surface_id").and_then(|v| v.as_str()) == Some(id) {
216        Liveness::Running
217    } else {
218        Liveness::NotRunning
219    }
220}
221
222pub fn probe(pid: u32, port: u16, id: &str) -> Liveness {
223    if port == 0 || !pid_exists(pid) {
224        return Liveness::NotRunning;
225    }
226    match probe_once(port, id, PROBE_TIMEOUT) {
227        Liveness::Unknown => probe_once(port, id, PROBE_RETRY_TIMEOUT),
228        other => other,
229    }
230}
231
232/// Returns true when the surface is running or its liveness cannot be determined.
233///
234/// An `Unknown` probe result is treated as running so a busy surface keeps its
235/// name and `blyte clean` leaves it alone.
236pub fn is_running(record: &SurfaceRecord) -> bool {
237    matches!(
238        probe(record.pid, record.port, &record.id),
239        Liveness::Running | Liveness::Unknown
240    )
241}
242
243pub fn pick_name(
244    default_base: &str,
245    requested: Option<&str>,
246    running_names: &[String],
247) -> Result<String, String> {
248    if let Some(name) = requested {
249        validate_surface_name(name)?;
250        if running_names.iter().any(|r| r == name) {
251            return Err(format!(
252                "a running surface is already named {name}; pass a different --name"
253            ));
254        }
255        return Ok(name.to_string());
256    }
257    if validate_surface_name(default_base).is_err() {
258        return Err(format!(
259            "the repository directory name {default_base} cannot be a surface name; pass --name"
260        ));
261    }
262    if !running_names.iter().any(|r| r == default_base) {
263        return Ok(default_base.to_string());
264    }
265    for suffix in 2u64.. {
266        let candidate = format!("{default_base}-{suffix}");
267        if !running_names.iter().any(|r| r == &candidate) {
268            validate_surface_name(&candidate)?;
269            return Ok(candidate);
270        }
271    }
272    unreachable!()
273}