1use std::io::{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::validate_surface_id;
8use serde::{Deserialize, Serialize};
9
10const PROBE_TIMEOUT: Duration = Duration::from_millis(300);
11
12static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct SurfaceRecord {
16 pub id: String,
17 pub name: String,
18 pub pid: u32,
19 pub port: u16,
20 pub session_id: String,
21 pub started_at: u64,
22}
23
24pub fn new_surface_id() -> Result<String, String> {
25 let mut bytes = [0u8; 8];
26 let mut file = std::fs::File::open("/dev/urandom")
27 .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
28 file.read_exact(&mut bytes)
29 .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
30 const HEX: &[u8; 16] = b"0123456789abcdef";
31 let mut out = String::with_capacity(17);
32 out.push('s');
33 for byte in bytes {
34 out.push(HEX[(byte >> 4) as usize] as char);
35 out.push(HEX[(byte & 0x0f) as usize] as char);
36 }
37 Ok(out)
38}
39
40pub fn validate_surface_name(name: &str) -> Result<(), String> {
41 let bytes = name.as_bytes();
42 let valid = !bytes.is_empty()
43 && bytes.len() <= 64
44 && bytes[0].is_ascii_alphanumeric()
45 && bytes
46 .iter()
47 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
48 if valid {
49 Ok(())
50 } else {
51 Err(format!(
52 "invalid surface name: {name} (use letters, digits, '.', '_' and '-', starting with a letter or digit)"
53 ))
54 }
55}
56
57pub fn surfaces_dir(main_checkout: &Path) -> PathBuf {
58 main_checkout.join(".wt").join("surfaces")
59}
60
61pub fn surface_dir(main_checkout: &Path, id: &str) -> PathBuf {
62 surfaces_dir(main_checkout).join(id)
63}
64
65pub fn record_path(main_checkout: &Path, id: &str) -> PathBuf {
66 surface_dir(main_checkout, id).join("surface.json")
67}
68
69pub fn entries_path(main_checkout: &Path, id: &str) -> PathBuf {
70 surface_dir(main_checkout, id).join("entries.jsonl")
71}
72
73pub fn write_record(main_checkout: &Path, record: &SurfaceRecord) -> Result<(), String> {
74 validate_surface_id(&record.id)?;
75 validate_surface_name(&record.name)?;
76 let dir = surface_dir(main_checkout, &record.id);
77 std::fs::create_dir_all(&dir)
78 .map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
79 let mut json = serde_json::to_string_pretty(record)
80 .map_err(|e| format!("failed to serialize surface record {}: {e}", record.id))?;
81 json.push('\n');
82 let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
83 let tmp = dir.join(format!("surface.json.tmp.{}.{seq}", std::process::id()));
84 let dest = record_path(main_checkout, &record.id);
85 if let Err(e) = std::fs::write(&tmp, json.as_bytes()) {
86 let _ = std::fs::remove_file(&tmp);
87 return Err(format!("failed to write {}: {e}", tmp.display()));
88 }
89 if let Err(e) = std::fs::rename(&tmp, &dest) {
90 let _ = std::fs::remove_file(&tmp);
91 return Err(format!(
92 "failed to rename {} to {}: {e}",
93 tmp.display(),
94 dest.display()
95 ));
96 }
97 Ok(())
98}
99
100pub fn read_record(main_checkout: &Path, id: &str) -> Result<SurfaceRecord, String> {
101 validate_surface_id(id)?;
102 let path = record_path(main_checkout, id);
103 let text = std::fs::read_to_string(&path)
104 .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
105 let record: SurfaceRecord = serde_json::from_str(&text)
106 .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
107 if record.id != id {
108 return Err(format!(
109 "surface record {} has id {}, expected {id}",
110 path.display(),
111 record.id
112 ));
113 }
114 if let Err(e) = validate_surface_name(&record.name) {
115 return Err(format!("surface record {} has {e}", path.display()));
116 }
117 Ok(record)
118}
119
120pub fn list_records(main_checkout: &Path) -> Result<Vec<SurfaceRecord>, String> {
121 let root = surfaces_dir(main_checkout);
122 let entries = match std::fs::read_dir(&root) {
123 Ok(entries) => entries,
124 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
125 Err(e) => return Err(format!("failed to read {}: {e}", root.display())),
126 };
127 let mut records = Vec::new();
128 for entry in entries {
129 let entry = entry.map_err(|e| format!("failed to read {}: {e}", root.display()))?;
130 let path = entry.path();
131 let file_type = entry
132 .file_type()
133 .map_err(|e| format!("failed to inspect {}: {e}", path.display()))?;
134 if !file_type.is_dir() {
135 continue;
136 }
137 let name_os = entry.file_name();
138 let Some(id) = name_os.to_str() else {
139 return Err(format!("invalid surface directory: {}", path.display()));
140 };
141 if let Err(e) = validate_surface_id(id) {
142 return Err(format!("invalid surface directory {}: {e}", path.display()));
143 }
144 let record = read_record(main_checkout, id)?;
145 records.push(record);
146 }
147 records.sort_by(|a, b| {
148 a.started_at
149 .cmp(&b.started_at)
150 .then_with(|| a.id.cmp(&b.id))
151 });
152 Ok(records)
153}
154
155pub fn health_matches(port: u16, id: &str) -> bool {
156 if port == 0 {
157 return false;
158 }
159 let addr = SocketAddr::from(([127, 0, 0, 1], port));
160 let mut stream = match TcpStream::connect_timeout(&addr, PROBE_TIMEOUT) {
161 Ok(s) => s,
162 Err(_) => return false,
163 };
164 if stream.set_read_timeout(Some(PROBE_TIMEOUT)).is_err() {
165 return false;
166 }
167 if stream.set_write_timeout(Some(PROBE_TIMEOUT)).is_err() {
168 return false;
169 }
170 let req =
171 format!("GET /api/health HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
172 if stream.write_all(req.as_bytes()).is_err() {
173 return false;
174 }
175 let mut raw = Vec::new();
176 if stream.read_to_end(&mut raw).is_err() {
177 return false;
178 }
179 let text = match std::str::from_utf8(&raw) {
180 Ok(s) => s,
181 Err(_) => return false,
182 };
183 let (head, body) = match text.split_once("\r\n\r\n") {
184 Some(parts) => parts,
185 None => return false,
186 };
187 let status_line = head.lines().next().unwrap_or("");
188 if !(status_line.starts_with("HTTP/1.1 200") || status_line.starts_with("HTTP/1.0 200")) {
189 return false;
190 }
191 let val: serde_json::Value = match serde_json::from_str(body) {
192 Ok(v) => v,
193 Err(_) => return false,
194 };
195 val.get("surface_id").and_then(|v| v.as_str()) == Some(id)
196}
197
198pub fn is_running(record: &SurfaceRecord) -> bool {
199 health_matches(record.port, &record.id)
200}
201
202pub fn pick_name(
203 default_base: &str,
204 requested: Option<&str>,
205 running_names: &[String],
206) -> Result<String, String> {
207 if let Some(name) = requested {
208 validate_surface_name(name)?;
209 if running_names.iter().any(|r| r == name) {
210 return Err(format!(
211 "a running surface is already named {name}; pass a different --name"
212 ));
213 }
214 return Ok(name.to_string());
215 }
216 if validate_surface_name(default_base).is_err() {
217 return Err(format!(
218 "the repository directory name {default_base} cannot be a surface name; pass --name"
219 ));
220 }
221 if !running_names.iter().any(|r| r == default_base) {
222 return Ok(default_base.to_string());
223 }
224 for suffix in 2u64.. {
225 let candidate = format!("{default_base}-{suffix}");
226 if !running_names.iter().any(|r| r == &candidate) {
227 validate_surface_name(&candidate)?;
228 return Ok(candidate);
229 }
230 }
231 unreachable!()
232}