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
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct LocatedRecord {
67    pub record: SurfaceRecord,
68    pub dir: PathBuf,
69}
70
71fn fnv1a_64(bytes: &[u8]) -> u64 {
72    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
73    for &byte in bytes {
74        hash ^= u64::from(byte);
75        hash = hash.wrapping_mul(0x0100_0000_01b3);
76    }
77    hash
78}
79
80fn path_bytes(path: &Path) -> std::borrow::Cow<'_, [u8]> {
81    #[cfg(unix)]
82    {
83        use std::os::unix::ffi::OsStrExt;
84        std::borrow::Cow::Borrowed(path.as_os_str().as_bytes())
85    }
86    #[cfg(not(unix))]
87    {
88        std::borrow::Cow::Owned(path.to_string_lossy().into_owned().into_bytes())
89    }
90}
91
92fn folder_store_key(canonical: &Path) -> String {
93    format!("{:016x}", fnv1a_64(&path_bytes(canonical)))
94}
95
96fn ensure_dir_0700(dir: &Path) -> Result<(), String> {
97    #[cfg(unix)]
98    {
99        use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
100        if let Some(parent) = dir.parent() {
101            std::fs::create_dir_all(parent)
102                .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
103        }
104        let mut builder = std::fs::DirBuilder::new();
105        builder.mode(0o700);
106        match builder.create(dir) {
107            Ok(()) => {}
108            Err(e) if e.kind() == ErrorKind::AlreadyExists => {
109                let meta = std::fs::metadata(dir)
110                    .map_err(|me| format!("failed to inspect {}: {me}", dir.display()))?;
111                if !meta.is_dir() {
112                    return Err(format!(
113                        "folder store {} exists and is not a directory",
114                        dir.display()
115                    ));
116                }
117                std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).map_err(
118                    |pe| format!("failed to set permissions on {}: {pe}", dir.display()),
119                )?;
120            }
121            Err(e) => return Err(format!("failed to create {}: {e}", dir.display())),
122        }
123        Ok(())
124    }
125    #[cfg(not(unix))]
126    {
127        std::fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))
128    }
129}
130
131fn verify_root_file(store_dir: &Path, canonical: &Path) -> Result<bool, String> {
132    let root_file = store_dir.join("root");
133    let raw = match std::fs::read(&root_file) {
134        Ok(bytes) => bytes,
135        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(false),
136        Err(e) => return Err(format!("failed to read {}: {e}", root_file.display())),
137    };
138    let stored = raw.strip_suffix(b"\n").unwrap_or(&raw);
139    let stored = stored.strip_suffix(b"\r").unwrap_or(stored);
140    let expected = path_bytes(canonical);
141    if stored != expected.as_ref() {
142        let stored_display = String::from_utf8_lossy(stored);
143        return Err(format!(
144            "folder store collision in {}: recorded root {} differs from {}",
145            store_dir.display(),
146            stored_display,
147            canonical.display()
148        ));
149    }
150    Ok(true)
151}
152
153pub fn folder_store(state_dir: &Path, root: &Path) -> Result<PathBuf, String> {
154    let canonical = root
155        .canonicalize()
156        .map_err(|e| format!("failed to canonicalize {}: {e}", root.display()))?;
157    let key = folder_store_key(&canonical);
158    let store_dir = state_dir.join("folders").join(key);
159    ensure_dir_0700(&store_dir)?;
160    if !verify_root_file(&store_dir, &canonical)? {
161        let root_file = store_dir.join("root");
162        let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
163        let tmp = store_dir.join(format!(".root.tmp.{}.{seq}", std::process::id()));
164        let content = path_bytes(&canonical);
165        if let Err(e) = std::fs::write(&tmp, content.as_ref()) {
166            let _ = std::fs::remove_file(&tmp);
167            return Err(format!("failed to write {}: {e}", tmp.display()));
168        }
169        if let Err(e) = std::fs::rename(&tmp, &root_file) {
170            let _ = std::fs::remove_file(&tmp);
171            return Err(format!(
172                "failed to rename {} to {}: {e}",
173                tmp.display(),
174                root_file.display()
175            ));
176        }
177    }
178    Ok(store_dir)
179}
180
181fn existing_folder_store(state_dir: &Path, root: &Path) -> Result<Option<PathBuf>, String> {
182    let canonical = match root.canonicalize() {
183        Ok(c) => c,
184        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
185        Err(e) => return Err(format!("failed to canonicalize {}: {e}", root.display())),
186    };
187    let key = folder_store_key(&canonical);
188    let store_dir = state_dir.join("folders").join(key);
189    match std::fs::metadata(&store_dir) {
190        Ok(meta) if meta.is_dir() => {
191            let _ = verify_root_file(&store_dir, &canonical)?;
192            Ok(Some(store_dir))
193        }
194        Ok(_) => Err(format!(
195            "folder store {} exists and is not a directory",
196            store_dir.display()
197        )),
198        Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
199        Err(e) => Err(format!("failed to inspect {}: {e}", store_dir.display())),
200    }
201}
202
203pub fn surfaces_dir(main_checkout: &Path) -> PathBuf {
204    main_checkout.join(".wt").join("surfaces")
205}
206
207pub fn surface_dir(main_checkout: &Path, id: &str) -> PathBuf {
208    surfaces_dir(main_checkout).join(id)
209}
210
211pub fn write_record_in(dir: &Path, record: &SurfaceRecord) -> Result<(), String> {
212    validate_surface_id(&record.id)?;
213    validate_surface_name(&record.name)?;
214    std::fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
215    let mut json = serde_json::to_string_pretty(record)
216        .map_err(|e| format!("failed to serialize surface record {}: {e}", record.id))?;
217    json.push('\n');
218    let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
219    let tmp = dir.join(format!("surface.json.tmp.{}.{seq}", std::process::id()));
220    let dest = dir.join("surface.json");
221    if let Err(e) = std::fs::write(&tmp, json.as_bytes()) {
222        let _ = std::fs::remove_file(&tmp);
223        return Err(format!("failed to write {}: {e}", tmp.display()));
224    }
225    if let Err(e) = std::fs::rename(&tmp, &dest) {
226        let _ = std::fs::remove_file(&tmp);
227        return Err(format!(
228            "failed to rename {} to {}: {e}",
229            tmp.display(),
230            dest.display()
231        ));
232    }
233    Ok(())
234}
235
236pub fn read_record_in(dir: &Path, id: &str) -> Result<SurfaceRecord, String> {
237    validate_surface_id(id)?;
238    let path = dir.join("surface.json");
239    let text = std::fs::read_to_string(&path)
240        .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
241    let record: SurfaceRecord = serde_json::from_str(&text)
242        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
243    if record.id != id {
244        return Err(format!(
245            "surface record {} has id {}, expected {id}",
246            path.display(),
247            record.id
248        ));
249    }
250    if let Err(e) = validate_surface_name(&record.name) {
251        return Err(format!("surface record {} has {e}", path.display()));
252    }
253    Ok(record)
254}
255
256pub fn read_record(main_checkout: &Path, id: &str) -> Result<SurfaceRecord, String> {
257    read_record_in(&surface_dir(main_checkout, id), id)
258}
259
260pub fn list_records_in(root: &Path) -> Result<Vec<LocatedRecord>, String> {
261    let entries = match std::fs::read_dir(root) {
262        Ok(entries) => entries,
263        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
264        Err(e) => return Err(format!("failed to read {}: {e}", root.display())),
265    };
266    let mut records = Vec::new();
267    for entry in entries {
268        let entry = entry.map_err(|e| format!("failed to read {}: {e}", root.display()))?;
269        let path = entry.path();
270        let file_type = entry
271            .file_type()
272            .map_err(|e| format!("failed to inspect {}: {e}", path.display()))?;
273        if !file_type.is_dir() {
274            continue;
275        }
276        let name_os = entry.file_name();
277        let Some(id) = name_os.to_str() else {
278            return Err(format!("invalid surface directory: {}", path.display()));
279        };
280        if let Err(e) = validate_surface_id(id) {
281            return Err(format!("invalid surface directory {}: {e}", path.display()));
282        }
283        let record = read_record_in(&path, id)?;
284        records.push(LocatedRecord { record, dir: path });
285    }
286    records.sort_by(|a, b| {
287        a.record
288            .started_at
289            .cmp(&b.record.started_at)
290            .then_with(|| a.record.id.cmp(&b.record.id))
291    });
292    Ok(records)
293}
294
295pub fn list_records_for_root(
296    root: &Path,
297    state_dir: Option<&Path>,
298) -> Result<Vec<LocatedRecord>, String> {
299    let mut records = list_records_in(&surfaces_dir(root))?;
300    if let Some(sd) = state_dir {
301        if let Some(store) = existing_folder_store(sd, root)? {
302            records.extend(list_records_in(&store.join("surfaces"))?);
303        }
304    }
305    records.sort_by(|a, b| {
306        a.record
307            .started_at
308            .cmp(&b.record.started_at)
309            .then_with(|| a.record.id.cmp(&b.record.id))
310    });
311    Ok(records)
312}
313
314fn pid_exists(pid: u32) -> bool {
315    let Ok(raw_pid) = libc::pid_t::try_from(pid) else {
316        return false;
317    };
318    if raw_pid <= 0 {
319        return false;
320    }
321    let ret = unsafe { libc::kill(raw_pid, 0) };
322    if ret == 0 {
323        return true;
324    }
325    !matches!(
326        std::io::Error::last_os_error().raw_os_error(),
327        Some(libc::ESRCH)
328    )
329}
330
331fn probe_once(port: u16, id: &str, timeout: Duration) -> Liveness {
332    let addr = SocketAddr::from(([127, 0, 0, 1], port));
333    let mut stream = match TcpStream::connect_timeout(&addr, timeout) {
334        Ok(s) => s,
335        Err(e) if e.kind() == ErrorKind::ConnectionRefused => return Liveness::NotRunning,
336        Err(_) => return Liveness::Unknown,
337    };
338    if stream.set_read_timeout(Some(timeout)).is_err() {
339        return Liveness::Unknown;
340    }
341    if stream.set_write_timeout(Some(timeout)).is_err() {
342        return Liveness::Unknown;
343    }
344    let req =
345        format!("GET /api/health HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
346    if stream.write_all(req.as_bytes()).is_err() {
347        return Liveness::Unknown;
348    }
349    let mut raw = Vec::new();
350    if stream.read_to_end(&mut raw).is_err() {
351        return Liveness::Unknown;
352    }
353    let Ok(text) = std::str::from_utf8(&raw) else {
354        return Liveness::NotRunning;
355    };
356    let Some((head, body)) = text.split_once("\r\n\r\n") else {
357        return Liveness::NotRunning;
358    };
359    let status_line = head.lines().next().unwrap_or("");
360    if !(status_line.starts_with("HTTP/1.1 200") || status_line.starts_with("HTTP/1.0 200")) {
361        return Liveness::NotRunning;
362    }
363    let Ok(val) = serde_json::from_str::<serde_json::Value>(body) else {
364        return Liveness::NotRunning;
365    };
366    if val.get("surface_id").and_then(|v| v.as_str()) == Some(id) {
367        Liveness::Running
368    } else {
369        Liveness::NotRunning
370    }
371}
372
373pub fn probe(pid: u32, port: u16, id: &str) -> Liveness {
374    if port == 0 || !pid_exists(pid) {
375        return Liveness::NotRunning;
376    }
377    match probe_once(port, id, PROBE_TIMEOUT) {
378        Liveness::Unknown => probe_once(port, id, PROBE_RETRY_TIMEOUT),
379        other => other,
380    }
381}
382
383/// Returns true when the surface is running or its liveness cannot be determined.
384///
385/// An `Unknown` probe result is treated as running so a busy surface keeps its
386/// name and `blyte clean` leaves it alone.
387pub fn is_running(record: &SurfaceRecord) -> bool {
388    matches!(
389        probe(record.pid, record.port, &record.id),
390        Liveness::Running | Liveness::Unknown
391    )
392}
393
394pub fn pick_name(
395    default_base: &str,
396    requested: Option<&str>,
397    running_names: &[String],
398) -> Result<String, String> {
399    if let Some(name) = requested {
400        validate_surface_name(name)?;
401        if running_names.iter().any(|r| r == name) {
402            return Err(format!(
403                "a running surface is already named {name}; pass a different --name"
404            ));
405        }
406        return Ok(name.to_string());
407    }
408    if validate_surface_name(default_base).is_err() {
409        return Err(format!(
410            "the repository directory name {default_base} cannot be a surface name; pass --name"
411        ));
412    }
413    if !running_names.iter().any(|r| r == default_base) {
414        return Ok(default_base.to_string());
415    }
416    for suffix in 2u64.. {
417        let candidate = format!("{default_base}-{suffix}");
418        if !running_names.iter().any(|r| r == &candidate) {
419            validate_surface_name(&candidate)?;
420            return Ok(candidate);
421        }
422    }
423    unreachable!()
424}