Skip to main content

blyte_cli/
surface_registry.rs

1use std::io::Write;
2use std::path::{Path, PathBuf};
3use std::sync::atomic::{AtomicU64, Ordering};
4
5use blyte_agent::sandbox::validate_surface_id;
6use serde::{Deserialize, Serialize};
7
8use crate::surface_dir::{probe, validate_surface_name, Liveness};
9
10static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct RegistryEntry {
14    pub id: String,
15    pub name: String,
16    pub root: PathBuf,
17    pub branch: String,
18    pub pid: u32,
19    pub port: u16,
20    pub started_at: u64,
21    pub doing: String,
22}
23
24pub fn registry_dir() -> Result<PathBuf, String> {
25    crate::registry::state_dir()
26        .map(|dir| dir.join("surfaces"))
27        .ok_or_else(|| {
28            "cannot find the blyte state directory: set BLYTE_STATE_DIR, XDG_STATE_HOME or HOME"
29                .to_string()
30        })
31}
32
33pub fn entry_path(dir: &Path, id: &str) -> PathBuf {
34    dir.join(format!("{id}.json"))
35}
36
37pub fn write_entry(dir: &Path, entry: &RegistryEntry) -> Result<(), String> {
38    validate_surface_id(&entry.id)?;
39    validate_surface_name(&entry.name)?;
40    std::fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
41    let dest = entry_path(dir, &entry.id);
42    let mut json = serde_json::to_string_pretty(entry)
43        .map_err(|e| format!("failed to serialize {}: {e}", dest.display()))?;
44    json.push('\n');
45    let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
46    let tmp = dir.join(format!(".{}.tmp.{}.{seq}", entry.id, std::process::id()));
47    let mut opts = std::fs::OpenOptions::new();
48    opts.write(true).create_new(true);
49    #[cfg(unix)]
50    {
51        use std::os::unix::fs::OpenOptionsExt;
52        opts.mode(0o600);
53    }
54    let mut file = opts
55        .open(&tmp)
56        .map_err(|e| format!("failed to create {}: {e}", tmp.display()))?;
57    if let Err(e) = file.write_all(json.as_bytes()) {
58        drop(file);
59        let _ = std::fs::remove_file(&tmp);
60        return Err(format!("failed to write {}: {e}", tmp.display()));
61    }
62    drop(file);
63    #[cfg(unix)]
64    {
65        use std::os::unix::fs::PermissionsExt;
66        if let Err(e) = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)) {
67            let _ = std::fs::remove_file(&tmp);
68            return Err(format!(
69                "failed to set permissions on {}: {e}",
70                tmp.display()
71            ));
72        }
73    }
74    if let Err(e) = std::fs::rename(&tmp, &dest) {
75        let _ = std::fs::remove_file(&tmp);
76        return Err(format!(
77            "failed to rename {} to {}: {e}",
78            tmp.display(),
79            dest.display()
80        ));
81    }
82    Ok(())
83}
84
85pub fn remove_entry(dir: &Path, id: &str) -> Result<(), String> {
86    let path = entry_path(dir, id);
87    match std::fs::remove_file(&path) {
88        Ok(()) => Ok(()),
89        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
90        Err(e) => Err(format!("failed to remove {}: {e}", path.display())),
91    }
92}
93
94pub fn read_entries(dir: &Path) -> Result<Vec<RegistryEntry>, String> {
95    let read_dir = match std::fs::read_dir(dir) {
96        Ok(rd) => rd,
97        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
98        Err(e) => return Err(format!("failed to read {}: {e}", dir.display())),
99    };
100    let mut entries = Vec::new();
101    for item in read_dir {
102        let item = item.map_err(|e| format!("failed to read {}: {e}", dir.display()))?;
103        let path = item.path();
104        let file_name = item.file_name();
105        let lossy = file_name.to_string_lossy();
106        if !lossy.ends_with(".json") {
107            continue;
108        }
109        let Some(name_str) = file_name.to_str() else {
110            return Err(format!("invalid registry entry path: {}", path.display()));
111        };
112        let Some(stem) = name_str.strip_suffix(".json") else {
113            continue;
114        };
115        // A surface removes its entry when it exits, which can happen between the listing above
116        // and this read: that surface is no longer running, so it is not in the result.
117        let text = match std::fs::read_to_string(&path) {
118            Ok(text) => text,
119            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
120            Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
121        };
122        let entry: RegistryEntry = serde_json::from_str(&text)
123            .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
124        if entry.id != stem {
125            return Err(format!(
126                "surface registry entry {} has id {}, expected {stem}",
127                path.display(),
128                entry.id
129            ));
130        }
131        entries.push(entry);
132    }
133    entries.sort_by(|a, b| {
134        a.started_at
135            .cmp(&b.started_at)
136            .then_with(|| a.id.cmp(&b.id))
137    });
138    Ok(entries)
139}
140
141pub fn live_entries(dir: &Path) -> Result<Vec<RegistryEntry>, String> {
142    let entries = read_entries(dir)?;
143    let mut live = Vec::with_capacity(entries.len());
144    for entry in entries {
145        match probe(entry.pid, entry.port, &entry.id) {
146            Liveness::Running | Liveness::Unknown => live.push(entry),
147            Liveness::NotRunning => remove_entry(dir, &entry.id)?,
148        }
149    }
150    Ok(live)
151}
152
153pub fn find_by_name(dir: &Path, name: &str) -> Result<RegistryEntry, String> {
154    let entries = live_entries(dir)?;
155    let mut matches: Vec<RegistryEntry> = entries
156        .into_iter()
157        .filter(|entry| entry.name == name || entry.id == name)
158        .collect();
159    match matches.len() {
160        0 => Err(format!("no running surface named {name}")),
161        1 => Ok(matches.remove(0)),
162        _ => {
163            let ids: Vec<&str> = matches.iter().map(|e| e.id.as_str()).collect();
164            Err(format!(
165                "more than one running surface is named {name}; use an id: {}",
166                ids.join(", ")
167            ))
168        }
169    }
170}
171
172pub fn set_doing(dir: &Path, id: &str, doing: &str) -> Result<(), String> {
173    let path = entry_path(dir, id);
174    let text = std::fs::read_to_string(&path)
175        .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
176    let mut entry: RegistryEntry = serde_json::from_str(&text)
177        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
178    if entry.id != id {
179        return Err(format!(
180            "surface registry entry {} has id {}, expected {id}",
181            path.display(),
182            entry.id
183        ));
184    }
185    entry.doing = doing.to_string();
186    write_entry(dir, &entry)
187}
188
189pub fn first_line(text: &str) -> String {
190    for line in text.lines() {
191        let trimmed = line.trim();
192        if !trimmed.is_empty() {
193            return trimmed.chars().take(120).collect();
194        }
195    }
196    String::new()
197}