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