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::{is_git_repository, 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);
12const STARTING_MARKER: &str = ".starting";
13
14static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Liveness {
18    Running,
19    NotRunning,
20    Unknown,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24pub struct SurfaceRecord {
25    pub id: String,
26    pub name: String,
27    pub pid: u32,
28    pub port: u16,
29    pub session_id: String,
30    pub started_at: u64,
31}
32
33pub fn new_surface_id() -> Result<String, String> {
34    let mut bytes = [0u8; 8];
35    let mut file = std::fs::File::open("/dev/urandom")
36        .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
37    file.read_exact(&mut bytes)
38        .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
39    const HEX: &[u8; 16] = b"0123456789abcdef";
40    let mut out = String::with_capacity(17);
41    out.push('s');
42    for byte in bytes {
43        out.push(HEX[(byte >> 4) as usize] as char);
44        out.push(HEX[(byte & 0x0f) as usize] as char);
45    }
46    Ok(out)
47}
48
49pub fn validate_surface_name(name: &str) -> Result<(), String> {
50    let bytes = name.as_bytes();
51    let valid = !bytes.is_empty()
52        && bytes.len() <= 64
53        && bytes[0].is_ascii_alphanumeric()
54        && bytes
55            .iter()
56            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
57    if valid {
58        Ok(())
59    } else {
60        Err(format!(
61            "invalid surface name: {name} (use letters, digits, '.', '_' and '-', starting with a letter or digit)"
62        ))
63    }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct LocatedRecord {
68    pub record: SurfaceRecord,
69    pub dir: PathBuf,
70}
71
72fn fnv1a_64(bytes: &[u8]) -> u64 {
73    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
74    for &byte in bytes {
75        hash ^= u64::from(byte);
76        hash = hash.wrapping_mul(0x0100_0000_01b3);
77    }
78    hash
79}
80
81fn path_bytes(path: &Path) -> std::borrow::Cow<'_, [u8]> {
82    #[cfg(unix)]
83    {
84        use std::os::unix::ffi::OsStrExt;
85        std::borrow::Cow::Borrowed(path.as_os_str().as_bytes())
86    }
87    #[cfg(not(unix))]
88    {
89        std::borrow::Cow::Owned(path.to_string_lossy().into_owned().into_bytes())
90    }
91}
92
93fn folder_store_key(canonical: &Path) -> String {
94    format!("{:016x}", fnv1a_64(&path_bytes(canonical)))
95}
96
97fn ensure_dir_0700(dir: &Path) -> Result<(), String> {
98    #[cfg(unix)]
99    {
100        use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
101        if let Some(parent) = dir.parent() {
102            std::fs::create_dir_all(parent)
103                .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
104        }
105        let mut builder = std::fs::DirBuilder::new();
106        builder.mode(0o700);
107        match builder.create(dir) {
108            Ok(()) => {}
109            Err(e) if e.kind() == ErrorKind::AlreadyExists => {
110                let meta = std::fs::metadata(dir)
111                    .map_err(|me| format!("failed to inspect {}: {me}", dir.display()))?;
112                if !meta.is_dir() {
113                    return Err(format!(
114                        "folder store {} exists and is not a directory",
115                        dir.display()
116                    ));
117                }
118                std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).map_err(
119                    |pe| format!("failed to set permissions on {}: {pe}", dir.display()),
120                )?;
121            }
122            Err(e) => return Err(format!("failed to create {}: {e}", dir.display())),
123        }
124        Ok(())
125    }
126    #[cfg(not(unix))]
127    {
128        std::fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))
129    }
130}
131
132fn verify_root_file(store_dir: &Path, canonical: &Path) -> Result<bool, String> {
133    let root_file = store_dir.join("root");
134    let raw = match std::fs::read(&root_file) {
135        Ok(bytes) => bytes,
136        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(false),
137        Err(e) => return Err(format!("failed to read {}: {e}", root_file.display())),
138    };
139    let stored = raw.strip_suffix(b"\n").unwrap_or(&raw);
140    let stored = stored.strip_suffix(b"\r").unwrap_or(stored);
141    let expected = path_bytes(canonical);
142    if stored != expected.as_ref() {
143        let stored_display = String::from_utf8_lossy(stored);
144        return Err(format!(
145            "folder store collision in {}: recorded root {} differs from {}",
146            store_dir.display(),
147            stored_display,
148            canonical.display()
149        ));
150    }
151    Ok(true)
152}
153
154pub fn folder_store(state_dir: &Path, root: &Path) -> Result<PathBuf, String> {
155    let canonical = root
156        .canonicalize()
157        .map_err(|e| format!("failed to canonicalize {}: {e}", root.display()))?;
158    let key = folder_store_key(&canonical);
159    let store_dir = state_dir.join("folders").join(key);
160    ensure_dir_0700(&store_dir)?;
161    if !verify_root_file(&store_dir, &canonical)? {
162        let root_file = store_dir.join("root");
163        let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
164        let tmp = store_dir.join(format!(".root.tmp.{}.{seq}", std::process::id()));
165        let content = path_bytes(&canonical);
166        if let Err(e) = std::fs::write(&tmp, content.as_ref()) {
167            let _ = std::fs::remove_file(&tmp);
168            return Err(format!("failed to write {}: {e}", tmp.display()));
169        }
170        if let Err(e) = std::fs::rename(&tmp, &root_file) {
171            let _ = std::fs::remove_file(&tmp);
172            return Err(format!(
173                "failed to rename {} to {}: {e}",
174                tmp.display(),
175                root_file.display()
176            ));
177        }
178    }
179    Ok(store_dir)
180}
181
182pub fn run_store(state_dir: &Path, root: &Path) -> Result<PathBuf, String> {
183    if is_git_repository(root) {
184        return Ok(root.join(".wt"));
185    }
186    let dir = folder_store(state_dir, root)?.join("runs");
187    ensure_dir_0700(&dir)?;
188    Ok(dir)
189}
190
191pub fn tasks_dir(state_dir: &Path, root: &Path) -> Result<PathBuf, String> {
192    if is_git_repository(root) {
193        return Ok(root.join(".wt").join("tasks"));
194    }
195    let dir = folder_store(state_dir, root)?.join("tasks");
196    ensure_dir_0700(&dir)?;
197    Ok(dir)
198}
199
200pub fn in_place_lock_path(state_dir: &Path, root: &Path) -> Result<PathBuf, String> {
201    if is_git_repository(root) {
202        return Err(format!(
203            "in-place runs are for folders that are not git repositories: {}",
204            root.display()
205        ));
206    }
207    Ok(folder_store(state_dir, root)?.join("in-place.lock"))
208}
209
210pub(crate) fn existing_folder_store(
211    state_dir: &Path,
212    root: &Path,
213) -> Result<Option<PathBuf>, String> {
214    let canonical = match root.canonicalize() {
215        Ok(c) => c,
216        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
217        Err(e) => return Err(format!("failed to canonicalize {}: {e}", root.display())),
218    };
219    let key = folder_store_key(&canonical);
220    let store_dir = state_dir.join("folders").join(key);
221    match std::fs::metadata(&store_dir) {
222        Ok(meta) if meta.is_dir() => {
223            let _ = verify_root_file(&store_dir, &canonical)?;
224            Ok(Some(store_dir))
225        }
226        Ok(_) => Err(format!(
227            "folder store {} exists and is not a directory",
228            store_dir.display()
229        )),
230        Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
231        Err(e) => Err(format!("failed to inspect {}: {e}", store_dir.display())),
232    }
233}
234
235pub fn surfaces_dir(main_checkout: &Path) -> PathBuf {
236    main_checkout.join(".wt").join("surfaces")
237}
238
239pub fn surface_dir(main_checkout: &Path, id: &str) -> PathBuf {
240    surfaces_dir(main_checkout).join(id)
241}
242
243pub fn prepare_starting_dir(dir: &Path) -> Result<(), String> {
244    let parent = dir
245        .parent()
246        .filter(|p| !p.as_os_str().is_empty())
247        .ok_or_else(|| format!("surface directory has no parent: {}", dir.display()))?;
248    let staging_parent = parent
249        .parent()
250        .filter(|p| !p.as_os_str().is_empty())
251        .ok_or_else(|| format!("surfaces directory has no parent: {}", parent.display()))?;
252    std::fs::create_dir_all(parent)
253        .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
254    let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
255    let staging_dir =
256        staging_parent.join(format!(".surface-starting.{}.{seq}", std::process::id()));
257    std::fs::create_dir(&staging_dir)
258        .map_err(|e| format!("failed to create {}: {e}", staging_dir.display()))?;
259    let marker = staging_dir.join(STARTING_MARKER);
260    if let Err(e) = std::fs::write(&marker, b"") {
261        let _ = std::fs::remove_dir_all(&staging_dir);
262        return Err(format!("failed to write {}: {e}", marker.display()));
263    }
264    if let Err(e) = std::fs::rename(&staging_dir, dir) {
265        let _ = std::fs::remove_dir_all(&staging_dir);
266        return Err(format!(
267            "failed to rename {} to {}: {e}",
268            staging_dir.display(),
269            dir.display()
270        ));
271    }
272    Ok(())
273}
274
275pub fn cleanup_starting_dir(dir: &Path) {
276    if dir.join("surface.json").exists() {
277        return;
278    }
279    if let Some(staging_parent) = dir
280        .parent()
281        .and_then(|p| p.parent())
282        .filter(|p| !p.as_os_str().is_empty())
283    {
284        let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
285        let trash = staging_parent.join(format!(".surface-cleanup.{}.{seq}", std::process::id()));
286        if std::fs::rename(dir, &trash).is_ok() {
287            let _ = std::fs::remove_dir_all(&trash);
288            return;
289        }
290    }
291    let _ = std::fs::remove_dir_all(dir);
292}
293
294pub fn write_record_in(dir: &Path, record: &SurfaceRecord) -> Result<(), String> {
295    validate_surface_id(&record.id)?;
296    validate_surface_name(&record.name)?;
297    std::fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
298    let mut json = serde_json::to_string_pretty(record)
299        .map_err(|e| format!("failed to serialize surface record {}: {e}", record.id))?;
300    json.push('\n');
301    let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
302    let tmp = dir.join(format!("surface.json.tmp.{}.{seq}", std::process::id()));
303    let dest = dir.join("surface.json");
304    if let Err(e) = std::fs::write(&tmp, json.as_bytes()) {
305        let _ = std::fs::remove_file(&tmp);
306        return Err(format!("failed to write {}: {e}", tmp.display()));
307    }
308    if let Err(e) = std::fs::rename(&tmp, &dest) {
309        let _ = std::fs::remove_file(&tmp);
310        return Err(format!(
311            "failed to rename {} to {}: {e}",
312            tmp.display(),
313            dest.display()
314        ));
315    }
316    let _ = std::fs::remove_file(dir.join(STARTING_MARKER));
317    Ok(())
318}
319
320fn parse_record_text(path: &Path, id: &str, text: &str) -> Result<SurfaceRecord, String> {
321    let record: SurfaceRecord = serde_json::from_str(text)
322        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
323    if record.id != id {
324        return Err(format!(
325            "surface record {} has id {}, expected {id}",
326            path.display(),
327            record.id
328        ));
329    }
330    if let Err(e) = validate_surface_name(&record.name) {
331        return Err(format!("surface record {} has {e}", path.display()));
332    }
333    Ok(record)
334}
335
336pub fn read_record_in(dir: &Path, id: &str) -> Result<SurfaceRecord, String> {
337    validate_surface_id(id)?;
338    let path = dir.join("surface.json");
339    let text = std::fs::read_to_string(&path)
340        .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
341    parse_record_text(&path, id, &text)
342}
343
344pub fn read_record(main_checkout: &Path, id: &str) -> Result<SurfaceRecord, String> {
345    read_record_in(&surface_dir(main_checkout, id), id)
346}
347
348pub fn list_records_in(root: &Path) -> Result<Vec<LocatedRecord>, String> {
349    let entries = match std::fs::read_dir(root) {
350        Ok(entries) => entries,
351        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
352        Err(e) => return Err(format!("failed to read {}: {e}", root.display())),
353    };
354    let mut records = Vec::new();
355    for entry in entries {
356        let entry = entry.map_err(|e| format!("failed to read {}: {e}", root.display()))?;
357        let path = entry.path();
358        let file_type = match entry.file_type() {
359            Ok(ft) => ft,
360            Err(e) if e.kind() == ErrorKind::NotFound => continue,
361            Err(e) => return Err(format!("failed to inspect {}: {e}", path.display())),
362        };
363        if !file_type.is_dir() {
364            continue;
365        }
366        let name_os = entry.file_name();
367        let Some(id) = name_os.to_str() else {
368            return Err(format!("invalid surface directory: {}", path.display()));
369        };
370        if let Err(e) = validate_surface_id(id) {
371            return Err(format!("invalid surface directory {}: {e}", path.display()));
372        }
373        let record_path = path.join("surface.json");
374        let record = match std::fs::read_to_string(&record_path) {
375            Ok(text) => parse_record_text(&record_path, id, &text)?,
376            Err(e) if e.kind() == ErrorKind::NotFound => {
377                if path.join(STARTING_MARKER).is_file() {
378                    continue;
379                }
380                match std::fs::read_to_string(&record_path) {
381                    Ok(text) => parse_record_text(&record_path, id, &text)?,
382                    Err(e2) if e2.kind() == ErrorKind::NotFound && !path.exists() => continue,
383                    Err(e2) => {
384                        return Err(format!("failed to read {}: {e2}", record_path.display()))
385                    }
386                }
387            }
388            Err(e) => return Err(format!("failed to read {}: {e}", record_path.display())),
389        };
390        records.push(LocatedRecord { record, dir: path });
391    }
392    records.sort_by(|a, b| {
393        a.record
394            .started_at
395            .cmp(&b.record.started_at)
396            .then_with(|| a.record.id.cmp(&b.record.id))
397    });
398    Ok(records)
399}
400
401pub fn list_records_for_root(
402    root: &Path,
403    state_dir: Option<&Path>,
404) -> Result<Vec<LocatedRecord>, String> {
405    let mut records = list_records_in(&surfaces_dir(root))?;
406    if let Some(sd) = state_dir {
407        if let Some(store) = existing_folder_store(sd, root)? {
408            records.extend(list_records_in(&store.join("surfaces"))?);
409        }
410    }
411    records.sort_by(|a, b| {
412        a.record
413            .started_at
414            .cmp(&b.record.started_at)
415            .then_with(|| a.record.id.cmp(&b.record.id))
416    });
417    Ok(records)
418}
419
420fn pid_exists(pid: u32) -> bool {
421    let Ok(raw_pid) = libc::pid_t::try_from(pid) else {
422        return false;
423    };
424    if raw_pid <= 0 {
425        return false;
426    }
427    let ret = unsafe { libc::kill(raw_pid, 0) };
428    if ret == 0 {
429        return true;
430    }
431    !matches!(
432        std::io::Error::last_os_error().raw_os_error(),
433        Some(libc::ESRCH)
434    )
435}
436
437fn probe_once(port: u16, id: &str, timeout: Duration) -> Liveness {
438    let addr = SocketAddr::from(([127, 0, 0, 1], port));
439    let mut stream = match TcpStream::connect_timeout(&addr, timeout) {
440        Ok(s) => s,
441        Err(e) if e.kind() == ErrorKind::ConnectionRefused => return Liveness::NotRunning,
442        Err(_) => return Liveness::Unknown,
443    };
444    if stream.set_read_timeout(Some(timeout)).is_err() {
445        return Liveness::Unknown;
446    }
447    if stream.set_write_timeout(Some(timeout)).is_err() {
448        return Liveness::Unknown;
449    }
450    let req =
451        format!("GET /api/health HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
452    if stream.write_all(req.as_bytes()).is_err() {
453        return Liveness::Unknown;
454    }
455    let mut raw = Vec::new();
456    if stream.read_to_end(&mut raw).is_err() {
457        return Liveness::Unknown;
458    }
459    let Ok(text) = std::str::from_utf8(&raw) else {
460        return Liveness::NotRunning;
461    };
462    let Some((head, body)) = text.split_once("\r\n\r\n") else {
463        return Liveness::NotRunning;
464    };
465    let status_line = head.lines().next().unwrap_or("");
466    if !(status_line.starts_with("HTTP/1.1 200") || status_line.starts_with("HTTP/1.0 200")) {
467        return Liveness::NotRunning;
468    }
469    let Ok(val) = serde_json::from_str::<serde_json::Value>(body) else {
470        return Liveness::NotRunning;
471    };
472    if val.get("surface_id").and_then(|v| v.as_str()) == Some(id) {
473        Liveness::Running
474    } else {
475        Liveness::NotRunning
476    }
477}
478
479pub fn probe(pid: u32, port: u16, id: &str) -> Liveness {
480    if port == 0 || !pid_exists(pid) {
481        return Liveness::NotRunning;
482    }
483    match probe_once(port, id, PROBE_TIMEOUT) {
484        Liveness::Unknown => probe_once(port, id, PROBE_RETRY_TIMEOUT),
485        other => other,
486    }
487}
488
489/// Returns true when the surface is running or its liveness cannot be determined.
490///
491/// An `Unknown` probe result is treated as running so a busy surface keeps its
492/// name and `blyte clean` leaves it alone.
493pub fn is_running(record: &SurfaceRecord) -> bool {
494    matches!(
495        probe(record.pid, record.port, &record.id),
496        Liveness::Running | Liveness::Unknown
497    )
498}
499
500pub fn pick_name(
501    default_base: &str,
502    requested: Option<&str>,
503    running_names: &[String],
504) -> Result<String, String> {
505    if let Some(name) = requested {
506        validate_surface_name(name)?;
507        if running_names.iter().any(|r| r == name) {
508            return Err(format!(
509                "a running surface is already named {name}; pass a different --name"
510            ));
511        }
512        return Ok(name.to_string());
513    }
514    if validate_surface_name(default_base).is_err() {
515        return Err(format!(
516            "the repository directory name {default_base} cannot be a surface name; pass --name"
517        ));
518    }
519    if !running_names.iter().any(|r| r == default_base) {
520        return Ok(default_base.to_string());
521    }
522    for suffix in 2u64.. {
523        let candidate = format!("{default_base}-{suffix}");
524        if !running_names.iter().any(|r| r == &candidate) {
525            validate_surface_name(&candidate)?;
526            return Ok(candidate);
527        }
528    }
529    unreachable!()
530}