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