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);
12
13static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Liveness {
17 Running,
18 NotRunning,
19 Unknown,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct SurfaceRecord {
24 pub id: String,
25 pub name: String,
26 pub pid: u32,
27 pub port: u16,
28 pub session_id: String,
29 pub started_at: u64,
30}
31
32pub fn new_surface_id() -> Result<String, String> {
33 let mut bytes = [0u8; 8];
34 let mut file = std::fs::File::open("/dev/urandom")
35 .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
36 file.read_exact(&mut bytes)
37 .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
38 const HEX: &[u8; 16] = b"0123456789abcdef";
39 let mut out = String::with_capacity(17);
40 out.push('s');
41 for byte in bytes {
42 out.push(HEX[(byte >> 4) as usize] as char);
43 out.push(HEX[(byte & 0x0f) as usize] as char);
44 }
45 Ok(out)
46}
47
48pub fn validate_surface_name(name: &str) -> Result<(), String> {
49 let bytes = name.as_bytes();
50 let valid = !bytes.is_empty()
51 && bytes.len() <= 64
52 && bytes[0].is_ascii_alphanumeric()
53 && bytes
54 .iter()
55 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
56 if valid {
57 Ok(())
58 } else {
59 Err(format!(
60 "invalid surface name: {name} (use letters, digits, '.', '_' and '-', starting with a letter or digit)"
61 ))
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct LocatedRecord {
67 pub record: SurfaceRecord,
68 pub dir: PathBuf,
69}
70
71fn fnv1a_64(bytes: &[u8]) -> u64 {
72 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
73 for &byte in bytes {
74 hash ^= u64::from(byte);
75 hash = hash.wrapping_mul(0x0100_0000_01b3);
76 }
77 hash
78}
79
80fn path_bytes(path: &Path) -> std::borrow::Cow<'_, [u8]> {
81 #[cfg(unix)]
82 {
83 use std::os::unix::ffi::OsStrExt;
84 std::borrow::Cow::Borrowed(path.as_os_str().as_bytes())
85 }
86 #[cfg(not(unix))]
87 {
88 std::borrow::Cow::Owned(path.to_string_lossy().into_owned().into_bytes())
89 }
90}
91
92fn folder_store_key(canonical: &Path) -> String {
93 format!("{:016x}", fnv1a_64(&path_bytes(canonical)))
94}
95
96fn ensure_dir_0700(dir: &Path) -> Result<(), String> {
97 #[cfg(unix)]
98 {
99 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
100 if let Some(parent) = dir.parent() {
101 std::fs::create_dir_all(parent)
102 .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
103 }
104 let mut builder = std::fs::DirBuilder::new();
105 builder.mode(0o700);
106 match builder.create(dir) {
107 Ok(()) => {}
108 Err(e) if e.kind() == ErrorKind::AlreadyExists => {
109 let meta = std::fs::metadata(dir)
110 .map_err(|me| format!("failed to inspect {}: {me}", dir.display()))?;
111 if !meta.is_dir() {
112 return Err(format!(
113 "folder store {} exists and is not a directory",
114 dir.display()
115 ));
116 }
117 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).map_err(
118 |pe| format!("failed to set permissions on {}: {pe}", dir.display()),
119 )?;
120 }
121 Err(e) => return Err(format!("failed to create {}: {e}", dir.display())),
122 }
123 Ok(())
124 }
125 #[cfg(not(unix))]
126 {
127 std::fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))
128 }
129}
130
131fn verify_root_file(store_dir: &Path, canonical: &Path) -> Result<bool, String> {
132 let root_file = store_dir.join("root");
133 let raw = match std::fs::read(&root_file) {
134 Ok(bytes) => bytes,
135 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(false),
136 Err(e) => return Err(format!("failed to read {}: {e}", root_file.display())),
137 };
138 let stored = raw.strip_suffix(b"\n").unwrap_or(&raw);
139 let stored = stored.strip_suffix(b"\r").unwrap_or(stored);
140 let expected = path_bytes(canonical);
141 if stored != expected.as_ref() {
142 let stored_display = String::from_utf8_lossy(stored);
143 return Err(format!(
144 "folder store collision in {}: recorded root {} differs from {}",
145 store_dir.display(),
146 stored_display,
147 canonical.display()
148 ));
149 }
150 Ok(true)
151}
152
153pub fn folder_store(state_dir: &Path, root: &Path) -> Result<PathBuf, String> {
154 let canonical = root
155 .canonicalize()
156 .map_err(|e| format!("failed to canonicalize {}: {e}", root.display()))?;
157 let key = folder_store_key(&canonical);
158 let store_dir = state_dir.join("folders").join(key);
159 ensure_dir_0700(&store_dir)?;
160 if !verify_root_file(&store_dir, &canonical)? {
161 let root_file = store_dir.join("root");
162 let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
163 let tmp = store_dir.join(format!(".root.tmp.{}.{seq}", std::process::id()));
164 let content = path_bytes(&canonical);
165 if let Err(e) = std::fs::write(&tmp, content.as_ref()) {
166 let _ = std::fs::remove_file(&tmp);
167 return Err(format!("failed to write {}: {e}", tmp.display()));
168 }
169 if let Err(e) = std::fs::rename(&tmp, &root_file) {
170 let _ = std::fs::remove_file(&tmp);
171 return Err(format!(
172 "failed to rename {} to {}: {e}",
173 tmp.display(),
174 root_file.display()
175 ));
176 }
177 }
178 Ok(store_dir)
179}
180
181pub fn run_store(state_dir: &Path, root: &Path) -> Result<PathBuf, String> {
182 if is_git_repository(root) {
183 return Ok(root.join(".wt"));
184 }
185 let dir = folder_store(state_dir, root)?.join("runs");
186 ensure_dir_0700(&dir)?;
187 Ok(dir)
188}
189
190pub fn tasks_dir(state_dir: &Path, root: &Path) -> Result<PathBuf, String> {
191 if is_git_repository(root) {
192 return Ok(root.join(".wt").join("tasks"));
193 }
194 let dir = folder_store(state_dir, root)?.join("tasks");
195 ensure_dir_0700(&dir)?;
196 Ok(dir)
197}
198
199pub fn in_place_lock_path(state_dir: &Path, root: &Path) -> Result<PathBuf, String> {
200 if is_git_repository(root) {
201 return Err(format!(
202 "in-place runs are for folders that are not git repositories: {}",
203 root.display()
204 ));
205 }
206 Ok(folder_store(state_dir, root)?.join("in-place.lock"))
207}
208
209pub(crate) fn existing_folder_store(
210 state_dir: &Path,
211 root: &Path,
212) -> Result<Option<PathBuf>, String> {
213 let canonical = match root.canonicalize() {
214 Ok(c) => c,
215 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
216 Err(e) => return Err(format!("failed to canonicalize {}: {e}", root.display())),
217 };
218 let key = folder_store_key(&canonical);
219 let store_dir = state_dir.join("folders").join(key);
220 match std::fs::metadata(&store_dir) {
221 Ok(meta) if meta.is_dir() => {
222 let _ = verify_root_file(&store_dir, &canonical)?;
223 Ok(Some(store_dir))
224 }
225 Ok(_) => Err(format!(
226 "folder store {} exists and is not a directory",
227 store_dir.display()
228 )),
229 Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
230 Err(e) => Err(format!("failed to inspect {}: {e}", store_dir.display())),
231 }
232}
233
234pub fn surfaces_dir(main_checkout: &Path) -> PathBuf {
235 main_checkout.join(".wt").join("surfaces")
236}
237
238pub fn surface_dir(main_checkout: &Path, id: &str) -> PathBuf {
239 surfaces_dir(main_checkout).join(id)
240}
241
242pub fn write_record_in(dir: &Path, record: &SurfaceRecord) -> Result<(), String> {
243 validate_surface_id(&record.id)?;
244 validate_surface_name(&record.name)?;
245 std::fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
246 let mut json = serde_json::to_string_pretty(record)
247 .map_err(|e| format!("failed to serialize surface record {}: {e}", record.id))?;
248 json.push('\n');
249 let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
250 let tmp = dir.join(format!("surface.json.tmp.{}.{seq}", std::process::id()));
251 let dest = dir.join("surface.json");
252 if let Err(e) = std::fs::write(&tmp, json.as_bytes()) {
253 let _ = std::fs::remove_file(&tmp);
254 return Err(format!("failed to write {}: {e}", tmp.display()));
255 }
256 if let Err(e) = std::fs::rename(&tmp, &dest) {
257 let _ = std::fs::remove_file(&tmp);
258 return Err(format!(
259 "failed to rename {} to {}: {e}",
260 tmp.display(),
261 dest.display()
262 ));
263 }
264 Ok(())
265}
266
267pub fn read_record_in(dir: &Path, id: &str) -> Result<SurfaceRecord, String> {
268 validate_surface_id(id)?;
269 let path = dir.join("surface.json");
270 let text = std::fs::read_to_string(&path)
271 .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
272 let record: SurfaceRecord = serde_json::from_str(&text)
273 .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
274 if record.id != id {
275 return Err(format!(
276 "surface record {} has id {}, expected {id}",
277 path.display(),
278 record.id
279 ));
280 }
281 if let Err(e) = validate_surface_name(&record.name) {
282 return Err(format!("surface record {} has {e}", path.display()));
283 }
284 Ok(record)
285}
286
287pub fn read_record(main_checkout: &Path, id: &str) -> Result<SurfaceRecord, String> {
288 read_record_in(&surface_dir(main_checkout, id), id)
289}
290
291pub fn list_records_in(root: &Path) -> Result<Vec<LocatedRecord>, String> {
292 let entries = match std::fs::read_dir(root) {
293 Ok(entries) => entries,
294 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
295 Err(e) => return Err(format!("failed to read {}: {e}", root.display())),
296 };
297 let mut records = Vec::new();
298 for entry in entries {
299 let entry = entry.map_err(|e| format!("failed to read {}: {e}", root.display()))?;
300 let path = entry.path();
301 let file_type = entry
302 .file_type()
303 .map_err(|e| format!("failed to inspect {}: {e}", path.display()))?;
304 if !file_type.is_dir() {
305 continue;
306 }
307 let name_os = entry.file_name();
308 let Some(id) = name_os.to_str() else {
309 return Err(format!("invalid surface directory: {}", path.display()));
310 };
311 if let Err(e) = validate_surface_id(id) {
312 return Err(format!("invalid surface directory {}: {e}", path.display()));
313 }
314 let record = read_record_in(&path, id)?;
315 records.push(LocatedRecord { record, dir: path });
316 }
317 records.sort_by(|a, b| {
318 a.record
319 .started_at
320 .cmp(&b.record.started_at)
321 .then_with(|| a.record.id.cmp(&b.record.id))
322 });
323 Ok(records)
324}
325
326pub fn list_records_for_root(
327 root: &Path,
328 state_dir: Option<&Path>,
329) -> Result<Vec<LocatedRecord>, String> {
330 let mut records = list_records_in(&surfaces_dir(root))?;
331 if let Some(sd) = state_dir {
332 if let Some(store) = existing_folder_store(sd, root)? {
333 records.extend(list_records_in(&store.join("surfaces"))?);
334 }
335 }
336 records.sort_by(|a, b| {
337 a.record
338 .started_at
339 .cmp(&b.record.started_at)
340 .then_with(|| a.record.id.cmp(&b.record.id))
341 });
342 Ok(records)
343}
344
345fn pid_exists(pid: u32) -> bool {
346 let Ok(raw_pid) = libc::pid_t::try_from(pid) else {
347 return false;
348 };
349 if raw_pid <= 0 {
350 return false;
351 }
352 let ret = unsafe { libc::kill(raw_pid, 0) };
353 if ret == 0 {
354 return true;
355 }
356 !matches!(
357 std::io::Error::last_os_error().raw_os_error(),
358 Some(libc::ESRCH)
359 )
360}
361
362fn probe_once(port: u16, id: &str, timeout: Duration) -> Liveness {
363 let addr = SocketAddr::from(([127, 0, 0, 1], port));
364 let mut stream = match TcpStream::connect_timeout(&addr, timeout) {
365 Ok(s) => s,
366 Err(e) if e.kind() == ErrorKind::ConnectionRefused => return Liveness::NotRunning,
367 Err(_) => return Liveness::Unknown,
368 };
369 if stream.set_read_timeout(Some(timeout)).is_err() {
370 return Liveness::Unknown;
371 }
372 if stream.set_write_timeout(Some(timeout)).is_err() {
373 return Liveness::Unknown;
374 }
375 let req =
376 format!("GET /api/health HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
377 if stream.write_all(req.as_bytes()).is_err() {
378 return Liveness::Unknown;
379 }
380 let mut raw = Vec::new();
381 if stream.read_to_end(&mut raw).is_err() {
382 return Liveness::Unknown;
383 }
384 let Ok(text) = std::str::from_utf8(&raw) else {
385 return Liveness::NotRunning;
386 };
387 let Some((head, body)) = text.split_once("\r\n\r\n") else {
388 return Liveness::NotRunning;
389 };
390 let status_line = head.lines().next().unwrap_or("");
391 if !(status_line.starts_with("HTTP/1.1 200") || status_line.starts_with("HTTP/1.0 200")) {
392 return Liveness::NotRunning;
393 }
394 let Ok(val) = serde_json::from_str::<serde_json::Value>(body) else {
395 return Liveness::NotRunning;
396 };
397 if val.get("surface_id").and_then(|v| v.as_str()) == Some(id) {
398 Liveness::Running
399 } else {
400 Liveness::NotRunning
401 }
402}
403
404pub fn probe(pid: u32, port: u16, id: &str) -> Liveness {
405 if port == 0 || !pid_exists(pid) {
406 return Liveness::NotRunning;
407 }
408 match probe_once(port, id, PROBE_TIMEOUT) {
409 Liveness::Unknown => probe_once(port, id, PROBE_RETRY_TIMEOUT),
410 other => other,
411 }
412}
413
414pub fn is_running(record: &SurfaceRecord) -> bool {
419 matches!(
420 probe(record.pid, record.port, &record.id),
421 Liveness::Running | Liveness::Unknown
422 )
423}
424
425pub fn pick_name(
426 default_base: &str,
427 requested: Option<&str>,
428 running_names: &[String],
429) -> Result<String, String> {
430 if let Some(name) = requested {
431 validate_surface_name(name)?;
432 if running_names.iter().any(|r| r == name) {
433 return Err(format!(
434 "a running surface is already named {name}; pass a different --name"
435 ));
436 }
437 return Ok(name.to_string());
438 }
439 if validate_surface_name(default_base).is_err() {
440 return Err(format!(
441 "the repository directory name {default_base} cannot be a surface name; pass --name"
442 ));
443 }
444 if !running_names.iter().any(|r| r == default_base) {
445 return Ok(default_base.to_string());
446 }
447 for suffix in 2u64.. {
448 let candidate = format!("{default_base}-{suffix}");
449 if !running_names.iter().any(|r| r == &candidate) {
450 validate_surface_name(&candidate)?;
451 return Ok(candidate);
452 }
453 }
454 unreachable!()
455}