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