blyte_cli/
surface_registry.rs1use 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::{health_matches, validate_surface_name};
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 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 if health_matches(entry.port, &entry.id) {
146 live.push(entry);
147 } else {
148 remove_entry(dir, &entry.id)?;
149 }
150 }
151 Ok(live)
152}
153
154pub fn find_by_name(dir: &Path, name: &str) -> Result<RegistryEntry, String> {
155 let entries = live_entries(dir)?;
156 let mut matches: Vec<RegistryEntry> = entries
157 .into_iter()
158 .filter(|entry| entry.name == name || entry.id == name)
159 .collect();
160 match matches.len() {
161 0 => Err(format!("no running surface named {name}")),
162 1 => Ok(matches.remove(0)),
163 _ => {
164 let ids: Vec<&str> = matches.iter().map(|e| e.id.as_str()).collect();
165 Err(format!(
166 "more than one running surface is named {name}; use an id: {}",
167 ids.join(", ")
168 ))
169 }
170 }
171}
172
173pub fn set_doing(dir: &Path, id: &str, doing: &str) -> Result<(), String> {
174 let path = entry_path(dir, id);
175 let text = std::fs::read_to_string(&path)
176 .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
177 let mut entry: RegistryEntry = serde_json::from_str(&text)
178 .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
179 if entry.id != id {
180 return Err(format!(
181 "surface registry entry {} has id {}, expected {id}",
182 path.display(),
183 entry.id
184 ));
185 }
186 entry.doing = doing.to_string();
187 write_entry(dir, &entry)
188}
189
190pub fn first_line(text: &str) -> String {
191 for line in text.lines() {
192 let trimmed = line.trim();
193 if !trimmed.is_empty() {
194 return trimmed.chars().take(120).collect();
195 }
196 }
197 String::new()
198}