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};
9use crate::surface_version::SurfaceRuntimeInfo;
10
11static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "lowercase")]
15pub enum SurfaceState {
16    Idle,
17    Working,
18    Approval,
19    Replied,
20}
21
22impl SurfaceState {
23    pub fn as_str(&self) -> &'static str {
24        match self {
25            Self::Idle => "idle",
26            Self::Working => "working",
27            Self::Approval => "approval",
28            Self::Replied => "replied",
29        }
30    }
31
32    pub fn display_label(&self) -> &'static str {
33        match self {
34            Self::Idle => "idle",
35            Self::Working => "working",
36            Self::Approval => "waiting on you (approval)",
37            Self::Replied => "waiting on you (replied)",
38        }
39    }
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct RegistryEntry {
44    pub id: String,
45    pub name: String,
46    pub root: PathBuf,
47    pub branch: Option<String>,
48    pub pid: u32,
49    pub port: u16,
50    pub started_at: u64,
51    pub doing: String,
52    pub state: SurfaceState,
53    #[serde(flatten)]
54    pub runtime: SurfaceRuntimeInfo,
55}
56
57pub fn state_dir() -> Result<PathBuf, String> {
58    crate::registry::state_dir().ok_or_else(|| {
59        "cannot find the blyte state directory: set BLYTE_STATE_DIR, XDG_STATE_HOME or HOME"
60            .to_string()
61    })
62}
63
64pub fn registry_dir() -> Result<PathBuf, String> {
65    state_dir().map(|dir| dir.join("surfaces"))
66}
67
68pub fn entry_path(dir: &Path, id: &str) -> PathBuf {
69    dir.join(format!("{id}.json"))
70}
71
72pub fn write_entry(dir: &Path, entry: &RegistryEntry) -> Result<(), String> {
73    validate_surface_id(&entry.id)?;
74    validate_surface_name(&entry.name)?;
75    entry.runtime.validate()?;
76    std::fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
77    let dest = entry_path(dir, &entry.id);
78    let mut json = serde_json::to_string_pretty(entry)
79        .map_err(|e| format!("failed to serialize {}: {e}", dest.display()))?;
80    json.push('\n');
81    let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
82    let tmp = dir.join(format!(".{}.tmp.{}.{seq}", entry.id, std::process::id()));
83    let mut opts = std::fs::OpenOptions::new();
84    opts.write(true).create_new(true);
85    #[cfg(unix)]
86    {
87        use std::os::unix::fs::OpenOptionsExt;
88        opts.mode(0o600);
89    }
90    let mut file = opts
91        .open(&tmp)
92        .map_err(|e| format!("failed to create {}: {e}", tmp.display()))?;
93    if let Err(e) = file.write_all(json.as_bytes()) {
94        drop(file);
95        let _ = std::fs::remove_file(&tmp);
96        return Err(format!("failed to write {}: {e}", tmp.display()));
97    }
98    drop(file);
99    #[cfg(unix)]
100    {
101        use std::os::unix::fs::PermissionsExt;
102        if let Err(e) = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)) {
103            let _ = std::fs::remove_file(&tmp);
104            return Err(format!(
105                "failed to set permissions on {}: {e}",
106                tmp.display()
107            ));
108        }
109    }
110    if let Err(e) = std::fs::rename(&tmp, &dest) {
111        let _ = std::fs::remove_file(&tmp);
112        return Err(format!(
113            "failed to rename {} to {}: {e}",
114            tmp.display(),
115            dest.display()
116        ));
117    }
118    Ok(())
119}
120
121pub fn remove_entry(dir: &Path, id: &str) -> Result<(), String> {
122    let path = entry_path(dir, id);
123    match std::fs::remove_file(&path) {
124        Ok(()) => Ok(()),
125        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
126        Err(e) => Err(format!("failed to remove {}: {e}", path.display())),
127    }
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct UnreadableRecord {
132    pub path: PathBuf,
133    pub reason: String,
134}
135
136#[derive(Debug, Clone, Default, PartialEq, Eq)]
137pub struct RegistryEntries {
138    pub entries: Vec<RegistryEntry>,
139    pub unreadable: Vec<UnreadableRecord>,
140}
141
142pub fn report_unreadable(unreadable: &[UnreadableRecord], err: &mut dyn Write) {
143    for record in unreadable {
144        let _ = writeln!(
145            err,
146            "blyte: skipped surface record {}: {}",
147            record.path.display(),
148            record.reason
149        );
150    }
151    if !unreadable.is_empty() {
152        let _ = err.flush();
153    }
154}
155
156pub fn read_entries(dir: &Path) -> Result<RegistryEntries, String> {
157    let read_dir = match std::fs::read_dir(dir) {
158        Ok(rd) => rd,
159        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(RegistryEntries::default()),
160        Err(e) => return Err(format!("failed to read {}: {e}", dir.display())),
161    };
162    let mut entries = Vec::new();
163    let mut unreadable = Vec::new();
164    for item in read_dir {
165        let item = item.map_err(|e| format!("failed to read {}: {e}", dir.display()))?;
166        let path = item.path();
167        let file_name = item.file_name();
168        let lossy = file_name.to_string_lossy();
169        if !lossy.ends_with(".json") {
170            continue;
171        }
172        let Some(name_str) = file_name.to_str() else {
173            return Err(format!("invalid registry entry path: {}", path.display()));
174        };
175        let Some(stem) = name_str.strip_suffix(".json") else {
176            continue;
177        };
178        // A surface removes its entry when it exits, which can happen between the listing above
179        // and this read: that surface is no longer running, so it is not in the result.
180        let bytes = match std::fs::read(&path) {
181            Ok(bytes) => bytes,
182            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
183            Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
184        };
185        let entry: RegistryEntry = match serde_json::from_slice(&bytes) {
186            Ok(entry) => entry,
187            Err(e) => {
188                unreadable.push(UnreadableRecord {
189                    path,
190                    reason: e.to_string(),
191                });
192                continue;
193            }
194        };
195        if entry.id != stem {
196            unreadable.push(UnreadableRecord {
197                path,
198                reason: format!("has id {}, expected {stem}", entry.id),
199            });
200            continue;
201        }
202        if let Err(reason) = entry.runtime.validate() {
203            unreadable.push(UnreadableRecord { path, reason });
204            continue;
205        }
206        entries.push(entry);
207    }
208    entries.sort_by(|a, b| {
209        a.started_at
210            .cmp(&b.started_at)
211            .then_with(|| a.id.cmp(&b.id))
212    });
213    unreadable.sort_by(|a, b| a.path.cmp(&b.path));
214    Ok(RegistryEntries {
215        entries,
216        unreadable,
217    })
218}
219
220pub fn live_entries(dir: &Path) -> Result<RegistryEntries, String> {
221    let read = read_entries(dir)?;
222    let mut live = Vec::with_capacity(read.entries.len());
223    for entry in read.entries {
224        match probe(entry.pid, entry.port, &entry.id) {
225            Liveness::Running | Liveness::Unknown => live.push(entry),
226            Liveness::NotRunning => remove_entry(dir, &entry.id)?,
227        }
228    }
229    Ok(RegistryEntries {
230        entries: live,
231        unreadable: read.unreadable,
232    })
233}
234
235pub fn find_by_name(dir: &Path, name: &str) -> Result<RegistryEntry, String> {
236    let listing = live_entries(dir)?;
237    let mut matches: Vec<RegistryEntry> = listing
238        .entries
239        .into_iter()
240        .filter(|entry| entry.name == name || entry.id == name)
241        .collect();
242    match matches.len() {
243        0 => {
244            if listing.unreadable.is_empty() {
245                Err(format!("no running surface named {name}"))
246            } else {
247                let paths: Vec<String> = listing
248                    .unreadable
249                    .iter()
250                    .map(|record| record.path.display().to_string())
251                    .collect();
252                let label = if paths.len() == 1 {
253                    "skipped unreadable surface record"
254                } else {
255                    "skipped unreadable surface records"
256                };
257                Err(format!(
258                    "no running surface named {name} ({label}: {})",
259                    paths.join(", ")
260                ))
261            }
262        }
263        1 => Ok(matches.remove(0)),
264        _ => {
265            let ids: Vec<&str> = matches.iter().map(|e| e.id.as_str()).collect();
266            Err(format!(
267                "more than one running surface is named {name}; use an id: {}",
268                ids.join(", ")
269            ))
270        }
271    }
272}
273
274pub fn first_line(text: &str) -> String {
275    for line in text.lines() {
276        let trimmed = line.trim();
277        if !trimmed.is_empty() {
278            return trimmed.chars().take(120).collect();
279        }
280    }
281    String::new()
282}