1use std::collections::BTreeSet;
2use std::fmt::Write as _;
3use std::io::{ErrorKind, Read, Write};
4use std::net::{SocketAddr, TcpStream};
5use std::path::{Path, PathBuf};
6use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
7
8use crate::serve::TOKEN_HEADER;
9use crate::session::{Entry, EntryBody};
10use crate::surface_dir::{is_running, list_records_for_root};
11use crate::surface_registry::{
12 find_by_name, first_line, live_entries, report_unreadable, RegistryEntry, SurfaceState,
13};
14
15const OPEN_CODE_TIMEOUT: Duration = Duration::from_secs(5);
16const RELOAD_WAIT_TIMEOUT: Duration = Duration::from_secs(20);
17const RELOAD_POLL_INTERVAL: Duration = Duration::from_millis(100);
18const MAX_OPEN_CODE_RESPONSE_BYTES: usize = 64 * 1024;
19const RUNS_WINDOW_DAYS: u64 = 14;
20
21#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
28pub struct StoppedSurface {
29 pub id: String,
30 pub name: String,
31 pub last_used: u64,
32 pub last_message: Option<String>,
33}
34
35fn scan_entries_summary(path: &Path) -> Result<(Option<u64>, Option<String>), String> {
36 let bytes = match std::fs::read(path) {
37 Ok(b) => b,
38 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((None, None)),
39 Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
40 };
41
42 let mut last_ts: Option<u64> = None;
43 let mut last_user_text: Option<String> = None;
44 let mut pos = 0usize;
45 let mut line_no = 0usize;
46 while pos < bytes.len() {
47 line_no += 1;
48 let start = pos;
49 let end = match bytes[pos..].iter().position(|&b| b == b'\n') {
50 Some(rel) => pos + rel + 1,
51 None => bytes.len(),
52 };
53 let is_last_without_newline = end == bytes.len() && !bytes[start..end].ends_with(b"\n");
54 let line_slice = &bytes[start..end];
55 let parsed = std::str::from_utf8(line_slice)
56 .map_err(|e| e.to_string())
57 .and_then(|s| serde_json::from_str::<Entry>(s).map_err(|e| e.to_string()));
58 match parsed {
59 Ok(entry) => {
60 last_ts = Some(entry.ts);
61 if let EntryBody::UserMessage { text, .. } = entry.body {
62 last_user_text = Some(text);
63 }
64 }
65 Err(reason) => {
66 if !is_last_without_newline {
67 return Err(format!(
68 "invalid entry in {} at line {}: {}",
69 path.display(),
70 line_no,
71 reason
72 ));
73 }
74 }
75 }
76 pos = end;
77 }
78
79 let last_message = last_user_text.and_then(|text| {
80 let line = first_line(&text);
81 if line.is_empty() {
82 None
83 } else {
84 Some(line)
85 }
86 });
87
88 Ok((last_ts, last_message))
89}
90
91fn stopped_surfaces_for_root(root: &Path, state_dir: &Path) -> Result<Vec<StoppedSurface>, String> {
92 let records = list_records_for_root(root, Some(state_dir))?;
93 let mut stopped = Vec::new();
94 for located in records {
95 if is_running(&located.record) {
96 continue;
97 }
98 let entries_path = located.dir.join("entries.jsonl");
99 let (last_ts, last_message) = scan_entries_summary(&entries_path)?;
100 let last_used = last_ts.unwrap_or(located.record.started_at);
101 stopped.push(StoppedSurface {
102 id: located.record.id,
103 name: located.record.name,
104 last_used,
105 last_message,
106 });
107 }
108 stopped.sort_by(|a, b| b.last_used.cmp(&a.last_used).then_with(|| a.id.cmp(&b.id)));
109 Ok(stopped)
110}
111
112pub fn stopped_surfaces(folder: &Path, state_dir: &Path) -> Result<Vec<StoppedSurface>, String> {
114 let root = crate::serve::resolve_folder(folder)?;
115 stopped_surfaces_for_root(&root, state_dir)
116}
117
118fn format_utc_minute(ts: u64) -> String {
119 let days = (ts / 86_400) as i64;
120 let secs_of_day = ts % 86_400;
121 let hour = secs_of_day / 3_600;
122 let min = (secs_of_day % 3_600) / 60;
123
124 let z = days + 719_468;
125 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
126 let doe = (z - era * 146_097) as u64;
127 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
128 let y = yoe as i64 + era * 400;
129 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
130 let mp = (5 * doy + 2) / 153;
131 let d = doy - (153 * mp + 2) / 5 + 1;
132 let m = if mp < 10 { mp + 3 } else { mp - 9 };
133 let year = if m <= 2 { y + 1 } else { y };
134
135 format!("{year:04}-{m:02}-{d:02} {hour:02}:{min:02}")
136}
137
138pub fn format_stopped_surfaces_table(entries: &[StoppedSurface], folder: &Path) -> String {
139 if entries.is_empty() {
140 return format!("no stopped surfaces in {}\n", folder.display());
141 }
142
143 let rows: Vec<(&str, &str, String, String)> = entries
144 .iter()
145 .map(|entry| {
146 let last_used = format_utc_minute(entry.last_used);
147 let message = match &entry.last_message {
148 Some(msg) => msg.chars().take(60).collect(),
149 None => "-".to_string(),
150 };
151 (entry.name.as_str(), entry.id.as_str(), last_used, message)
152 })
153 .collect();
154
155 let name_w = rows
156 .iter()
157 .map(|row| row.0.chars().count())
158 .max()
159 .unwrap_or(0)
160 .max("NAME".len());
161 let id_w = rows
162 .iter()
163 .map(|row| row.1.chars().count())
164 .max()
165 .unwrap_or(0)
166 .max("ID".len());
167 let used_w = rows
168 .iter()
169 .map(|row| row.2.chars().count())
170 .max()
171 .unwrap_or(0)
172 .max("LAST USED".len());
173
174 let mut out = String::new();
175 let _ = writeln!(
176 out,
177 "{:<name_w$} {:<id_w$} {:<used_w$} LAST MESSAGE",
178 "NAME", "ID", "LAST USED"
179 );
180 for (name, id, last_used, message) in rows {
181 let _ = writeln!(
182 out,
183 "{name:<name_w$} {id:<id_w$} {last_used:<used_w$} {message}"
184 );
185 }
186 let _ = writeln!(out);
187 let _ = writeln!(out, "resume with: blyte --resume <name or id>");
188 out
189}
190
191pub fn run_stopped_surfaces(
192 folder: &Path,
193 state_dir: &Path,
194 json: bool,
195 out: &mut dyn Write,
196 err: &mut dyn Write,
197) -> i32 {
198 let root = match crate::serve::resolve_folder(folder) {
199 Ok(root) => root,
200 Err(e) => {
201 let _ = writeln!(err, "blyte: {e}");
202 return 1;
203 }
204 };
205 let entries = match stopped_surfaces_for_root(&root, state_dir) {
206 Ok(entries) => entries,
207 Err(e) => {
208 let _ = writeln!(err, "blyte: {e}");
209 return 1;
210 }
211 };
212
213 if json {
214 match serde_json::to_string_pretty(&entries) {
215 Ok(text) => {
216 let _ = writeln!(out, "{text}");
217 return 0;
218 }
219 Err(e) => {
220 let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
221 return 1;
222 }
223 }
224 }
225
226 let _ = write!(out, "{}", format_stopped_surfaces_table(&entries, &root));
227 0
228}
229
230fn repository_name(root: &Path) -> String {
231 root.file_name()
232 .map(|name| name.to_string_lossy().into_owned())
233 .unwrap_or_else(|| root.display().to_string())
234}
235
236fn count_running_runs_at(root: &Path, now: SystemTime) -> Result<usize, String> {
237 let now = now
238 .duration_since(UNIX_EPOCH)
239 .map_err(|e| format!("system clock is before UNIX_EPOCH: {e}"))?
240 .as_secs();
241 crate::live_runs::collect(root, now, RUNS_WINDOW_DAYS).map(|live| live.running.len())
242}
243
244pub fn count_running_runs(root: &Path) -> Result<usize, String> {
245 count_running_runs_at(root, SystemTime::now())
246}
247
248fn format_surface_state(entry: &RegistryEntry) -> String {
249 if entry.state != SurfaceState::Idle {
250 return entry.state.display_label().to_string();
251 }
252 match count_running_runs(&entry.root) {
253 Ok(0) => entry.state.display_label().to_string(),
254 Ok(1) => "idle (1 run working)".to_string(),
255 Ok(n) => format!("idle ({n} runs working)"),
256 Err(err) => format!("idle (runs unknown: {err})"),
257 }
258}
259
260fn format_surface_version(entry: &RegistryEntry) -> String {
261 match entry.runtime.is_stale() {
262 Ok(false) => entry.runtime.version.clone(),
263 Ok(true) => format!("{} (stale)", entry.runtime.version),
264 Err(err) => format!("{} (stale unknown: {err})", entry.runtime.version),
265 }
266}
267
268#[derive(serde::Serialize)]
269struct SurfaceJsonEntry<'a> {
270 #[serde(flatten)]
271 entry: &'a RegistryEntry,
272 stale: Option<bool>,
273 #[serde(skip_serializing_if = "Option::is_none")]
274 stale_error: Option<String>,
275 runs_working: Option<usize>,
276 #[serde(skip_serializing_if = "Option::is_none")]
277 runs_error: Option<String>,
278}
279
280pub fn format_surfaces_table(entries: &[RegistryEntry], current_id: Option<&str>) -> String {
281 if entries.is_empty() {
282 return "no surfaces are running\n".to_string();
283 }
284
285 let rows: Vec<(String, String, &str, String, String, &str)> = entries
286 .iter()
287 .map(|entry| {
288 let name = if current_id == Some(entry.id.as_str()) {
289 format!("{} (this surface)", entry.name)
290 } else {
291 entry.name.clone()
292 };
293 (
294 name,
295 repository_name(&entry.root),
296 entry.branch.as_deref().unwrap_or("-"),
297 format_surface_version(entry),
298 format_surface_state(entry),
299 entry.doing.as_str(),
300 )
301 })
302 .collect();
303
304 let name_w = rows
305 .iter()
306 .map(|row| row.0.chars().count())
307 .max()
308 .unwrap_or(0)
309 .max("NAME".len());
310 let repo_w = rows
311 .iter()
312 .map(|row| row.1.chars().count())
313 .max()
314 .unwrap_or(0)
315 .max("REPOSITORY".len());
316 let branch_w = rows
317 .iter()
318 .map(|row| row.2.chars().count())
319 .max()
320 .unwrap_or(0)
321 .max("BRANCH".len());
322 let version_w = rows
323 .iter()
324 .map(|row| row.3.chars().count())
325 .max()
326 .unwrap_or(0)
327 .max("VERSION".len());
328 let state_w = rows
329 .iter()
330 .map(|row| row.4.chars().count())
331 .max()
332 .unwrap_or(0)
333 .max("STATE".len());
334
335 let mut out = String::new();
336 let _ = writeln!(
337 out,
338 "{:<name_w$} {:<repo_w$} {:<branch_w$} {:<version_w$} {:<state_w$} DOING",
339 "NAME", "REPOSITORY", "BRANCH", "VERSION", "STATE"
340 );
341 for (name, repo, branch, version, state, doing) in rows {
342 let _ = writeln!(
343 out,
344 "{name:<name_w$} {repo:<repo_w$} {branch:<branch_w$} {version:<version_w$} {state:<state_w$} {doing}"
345 );
346 }
347 out
348}
349
350pub fn run_surfaces(dir: &Path, json: bool, out: &mut dyn Write, err: &mut dyn Write) -> i32 {
351 let listing = match live_entries(dir) {
352 Ok(listing) => listing,
353 Err(e) => {
354 let _ = writeln!(err, "blyte: {e}");
355 return 1;
356 }
357 };
358 report_unreadable(&listing.unreadable, err);
359
360 if json {
361 let payload: Vec<SurfaceJsonEntry<'_>> = listing
362 .entries
363 .iter()
364 .map(|entry| {
365 let (stale, stale_error) = match entry.runtime.is_stale() {
366 Ok(stale) => (Some(stale), None),
367 Err(stale_err) => (None, Some(stale_err)),
368 };
369 let (runs_working, runs_error) = match count_running_runs(&entry.root) {
370 Ok(count) => (Some(count), None),
371 Err(runs_err) => (None, Some(runs_err)),
372 };
373 SurfaceJsonEntry {
374 entry,
375 stale,
376 stale_error,
377 runs_working,
378 runs_error,
379 }
380 })
381 .collect();
382 match serde_json::to_string_pretty(&payload) {
383 Ok(text) => {
384 let _ = writeln!(out, "{text}");
385 return 0;
386 }
387 Err(e) => {
388 let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
389 return 1;
390 }
391 }
392 }
393
394 let _ = write!(out, "{}", format_surfaces_table(&listing.entries, None));
395 0
396}
397
398fn read_surface_token(entry: &RegistryEntry) -> Result<String, String> {
399 let token_path = blyte_agent::sandbox::surface_token_path_for_id(&entry.id)?;
400 let raw_token = std::fs::read_to_string(&token_path).map_err(|_| {
401 format!(
402 "surface {} has no usable token at {}",
403 entry.name,
404 token_path.display()
405 )
406 })?;
407 let token = raw_token.trim();
408 if token.is_empty() || token.contains(['\n', '\r']) {
409 return Err(format!(
410 "surface {} has no usable token at {}",
411 entry.name,
412 token_path.display()
413 ));
414 }
415 Ok(token.to_string())
416}
417
418pub fn surface_url(entry: &RegistryEntry) -> Result<String, String> {
419 let token = read_surface_token(entry)?;
420 Ok(format!("http://127.0.0.1:{}/#token={token}", entry.port))
421}
422
423fn parse_http_status(head: &str) -> Result<u16, String> {
424 let status_line = head.lines().next().unwrap_or("").trim_end_matches('\r');
425 let mut parts = status_line.split_whitespace();
426 let version = parts
427 .next()
428 .ok_or_else(|| "empty HTTP response".to_string())?;
429 if !version.starts_with("HTTP/") {
430 return Err("invalid HTTP response".to_string());
431 }
432 let code_str = parts
433 .next()
434 .ok_or_else(|| "missing HTTP status code".to_string())?;
435 code_str
436 .parse::<u16>()
437 .map_err(|_| "invalid HTTP status code".to_string())
438}
439
440pub fn request_open_code(entry: &RegistryEntry, token: &str) -> Result<String, String> {
441 request_open_code_at(&entry.name, entry.port, token)
442}
443
444pub fn request_open_code_at(name: &str, port: u16, token: &str) -> Result<String, String> {
445 let deadline = Instant::now() + OPEN_CODE_TIMEOUT;
446 let addr = SocketAddr::from(([127, 0, 0, 1], port));
447 let mut stream = TcpStream::connect_timeout(&addr, OPEN_CODE_TIMEOUT).map_err(|e| {
448 if e.kind() == ErrorKind::ConnectionRefused {
449 format!("surface {name} refused the connection on port {port}")
450 } else {
451 format!("cannot connect to surface {name} on port {port}: {e}")
452 }
453 })?;
454
455 let remaining = deadline.saturating_duration_since(Instant::now());
456 if remaining.is_zero() {
457 return Err(format!("surface {name} timed out on port {port}"));
458 }
459 let _ = stream.set_write_timeout(Some(remaining));
460
461 let req = format!(
462 "POST /api/session/open-codes HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"
463 );
464 stream
465 .write_all(req.as_bytes())
466 .map_err(|e| format!("failed to request an open code from surface {name}: {e}"))?;
467
468 let mut raw = Vec::new();
469 let mut chunk = [0u8; 4096];
470 loop {
471 if raw.len() >= MAX_OPEN_CODE_RESPONSE_BYTES {
472 return Err(format!(
473 "surface {name} gave an answer blyte does not understand"
474 ));
475 }
476 let remaining = deadline.saturating_duration_since(Instant::now());
477 if remaining.is_zero() {
478 return Err(format!("surface {name} timed out on port {port}"));
479 }
480 let _ = stream.set_read_timeout(Some(remaining));
481 let max_read = (MAX_OPEN_CODE_RESPONSE_BYTES - raw.len()).min(chunk.len());
482 match stream.read(&mut chunk[..max_read]) {
483 Ok(0) => break,
484 Ok(n) => raw.extend_from_slice(&chunk[..n]),
485 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
486 Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
487 return Err(format!("surface {name} timed out on port {port}"));
488 }
489 Err(e) => {
490 return Err(format!("failed to read answer from surface {name}: {e}"));
491 }
492 }
493 }
494
495 let text = std::str::from_utf8(&raw)
496 .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
497 let (head, resp_body) = text
498 .split_once("\r\n\r\n")
499 .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
500 let status = parse_http_status(head)
501 .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
502 if status != 200 {
503 return Err(format!(
504 "surface {name} could not create an open code (HTTP {status})"
505 ));
506 }
507 let parsed: serde_json::Value = serde_json::from_str(resp_body)
508 .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
509 let code = parsed
510 .get("code")
511 .and_then(|v| v.as_str())
512 .map(str::trim)
513 .filter(|s| !s.is_empty())
514 .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
515 Ok(code.to_string())
516}
517
518fn known_folders(state_dir: &Path, entries: &[RegistryEntry]) -> Result<Vec<String>, String> {
519 let mut folders = BTreeSet::new();
520 let repos_path = state_dir.join("repos");
521 match std::fs::read_to_string(&repos_path) {
522 Ok(content) => {
523 for line in content.lines() {
524 let trimmed = line.trim();
525 if trimmed.is_empty() {
526 continue;
527 }
528 let path = PathBuf::from(trimmed);
529 if path.is_dir() {
530 folders.insert(trimmed.to_string());
531 }
532 }
533 }
534 Err(e) if e.kind() == ErrorKind::NotFound => {}
535 Err(e) => {
536 return Err(format!("failed to read {}: {e}", repos_path.display()));
537 }
538 }
539 for entry in entries {
540 folders.insert(entry.root.to_string_lossy().into_owned());
541 }
542 Ok(folders.into_iter().collect())
543}
544
545pub fn surfaces_payload(
546 registry_dir: &Path,
547 state_dir: &Path,
548 current_id: &str,
549 stopped: &[StoppedSurface],
550) -> Result<serde_json::Value, String> {
551 let listing = live_entries(registry_dir)?;
552 let mut entries = listing.entries;
553 entries.sort_by(|a, b| {
554 a.name
555 .cmp(&b.name)
556 .then_with(|| a.started_at.cmp(&b.started_at))
557 });
558 if !entries.iter().any(|entry| entry.id == current_id) {
559 return Err(format!(
560 "current surface {current_id} is not in the surface registry"
561 ));
562 }
563 let folders = known_folders(state_dir, &entries)?;
564 let surfaces: Vec<serde_json::Value> = entries
565 .iter()
566 .map(|entry| {
567 let (url, error) = match surface_url(entry) {
568 Ok(url) => (Some(url), None),
569 Err(err) => (None, Some(err)),
570 };
571 let (stale, stale_error) = match entry.runtime.is_stale() {
572 Ok(stale) => (Some(stale), None),
573 Err(err) => (None, Some(err)),
574 };
575 serde_json::json!({
576 "id": entry.id,
577 "name": entry.name,
578 "root": entry.root.to_string_lossy(),
579 "branch": entry.branch,
580 "doing": entry.doing,
581 "state": entry.state,
582 "version": entry.runtime.version,
583 "boot_id": entry.runtime.boot_id,
584 "stale": stale,
585 "stale_error": stale_error,
586 "current": entry.id == current_id,
587 "url": url,
588 "error": error,
589 })
590 })
591 .collect();
592 let unreadable: Vec<serde_json::Value> = listing
593 .unreadable
594 .iter()
595 .map(|record| {
596 serde_json::json!({
597 "path": record.path.to_string_lossy(),
598 "reason": record.reason,
599 })
600 })
601 .collect();
602 Ok(serde_json::json!({
603 "surfaces": surfaces,
604 "stopped": stopped,
605 "folders": folders,
606 "unreadable": unreadable,
607 }))
608}
609
610pub fn run_open(
611 dir: &Path,
612 name: &str,
613 opener: &dyn Fn(&str),
614 out: &mut dyn Write,
615 err: &mut dyn Write,
616) -> i32 {
617 let entry = match find_by_name(dir, name) {
618 Ok(entry) => entry,
619 Err(e) => {
620 let _ = writeln!(err, "blyte: {e}");
621 return 1;
622 }
623 };
624
625 let token = match read_surface_token(&entry) {
626 Ok(token) => token,
627 Err(e) => {
628 let _ = writeln!(err, "blyte: {e}");
629 return 1;
630 }
631 };
632
633 let code = match request_open_code(&entry, &token) {
634 Ok(code) => code,
635 Err(e) => {
636 let _ = writeln!(err, "blyte: {e}");
637 return 1;
638 }
639 };
640
641 let url = format!("http://127.0.0.1:{}/#open={code}", entry.port);
642 opener(&url);
643 let _ = writeln!(out, "blyte: opened surface {}", entry.name);
644 0
645}
646
647fn http_json_request(
648 name: &str,
649 port: u16,
650 method: &str,
651 path: &str,
652 token: &str,
653 body: Option<&str>,
654 timeout: Duration,
655) -> Result<(u16, String), String> {
656 let deadline = Instant::now() + timeout;
657 let addr = SocketAddr::from(([127, 0, 0, 1], port));
658 let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| {
659 if e.kind() == ErrorKind::ConnectionRefused {
660 format!("surface {name} refused the connection on port {port}")
661 } else {
662 format!("cannot connect to surface {name} on port {port}: {e}")
663 }
664 })?;
665
666 let remaining = deadline.saturating_duration_since(Instant::now());
667 if remaining.is_zero() {
668 return Err(format!("surface {name} timed out on port {port}"));
669 }
670 let _ = stream.set_write_timeout(Some(remaining));
671
672 let req = match body {
673 Some(payload) => format!(
674 "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
675 payload.len()
676 ),
677 None => format!(
678 "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nConnection: close\r\n\r\n"
679 ),
680 };
681 stream
682 .write_all(req.as_bytes())
683 .map_err(|e| format!("failed to contact surface {name}: {e}"))?;
684
685 let mut raw = Vec::new();
686 let mut chunk = [0u8; 4096];
687 loop {
688 if raw.len() >= MAX_OPEN_CODE_RESPONSE_BYTES {
689 return Err(format!(
690 "surface {name} gave an answer blyte does not understand"
691 ));
692 }
693 let remaining = deadline.saturating_duration_since(Instant::now());
694 if remaining.is_zero() {
695 return Err(format!("surface {name} timed out on port {port}"));
696 }
697 let _ = stream.set_read_timeout(Some(remaining));
698 let max_read = (MAX_OPEN_CODE_RESPONSE_BYTES - raw.len()).min(chunk.len());
699 match stream.read(&mut chunk[..max_read]) {
700 Ok(0) => break,
701 Ok(n) => raw.extend_from_slice(&chunk[..n]),
702 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
703 Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
704 return Err(format!("surface {name} timed out on port {port}"));
705 }
706 Err(e) => {
707 return Err(format!("failed to read answer from surface {name}: {e}"));
708 }
709 }
710 }
711
712 let text = std::str::from_utf8(&raw)
713 .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
714 let (head, resp_body) = text
715 .split_once("\r\n\r\n")
716 .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
717 let status = parse_http_status(head)
718 .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
719 Ok((status, resp_body.to_string()))
720}
721
722pub fn request_reload(entry: &RegistryEntry, token: &str) -> Result<(), String> {
723 let (status, resp_body) = http_json_request(
724 &entry.name,
725 entry.port,
726 "POST",
727 "/api/reload",
728 token,
729 Some("{}"),
730 OPEN_CODE_TIMEOUT,
731 )?;
732 if status != 200 {
733 let detail = serde_json::from_str::<serde_json::Value>(&resp_body)
734 .ok()
735 .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string));
736 return match detail {
737 Some(msg) if !msg.trim().is_empty() => Err(format!(
738 "surface {} failed to reload (HTTP {status}): {msg}",
739 entry.name
740 )),
741 _ => Err(format!(
742 "surface {} failed to reload (HTTP {status})",
743 entry.name
744 )),
745 };
746 }
747 let parsed: serde_json::Value = serde_json::from_str(&resp_body).map_err(|_| {
748 format!(
749 "surface {} gave an answer blyte does not understand",
750 entry.name
751 )
752 })?;
753 if parsed.get("reloading").and_then(|v| v.as_bool()) != Some(true) {
754 return Err(format!(
755 "surface {} gave an answer blyte does not understand",
756 entry.name
757 ));
758 }
759 Ok(())
760}
761
762fn wait_for_reloaded_surface(
763 entry: &RegistryEntry,
764 token: &str,
765 timeout: Duration,
766) -> Result<(String, String), String> {
767 let deadline = Instant::now() + timeout;
768 let mut last_error: Option<String> = None;
769 while Instant::now() < deadline {
770 let remaining = deadline.saturating_duration_since(Instant::now());
771 let step_timeout = remaining.min(Duration::from_secs(2));
772 match http_json_request(
773 &entry.name,
774 entry.port,
775 "GET",
776 "/api/session",
777 token,
778 None,
779 step_timeout,
780 ) {
781 Ok((200, body)) => {
782 if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&body) {
783 if let (Some(boot_id), Some(version)) = (
784 parsed
785 .get("boot_id")
786 .and_then(|v| v.as_str())
787 .map(str::trim),
788 parsed
789 .get("version")
790 .and_then(|v| v.as_str())
791 .map(str::trim),
792 ) {
793 if !boot_id.is_empty() && boot_id != entry.runtime.boot_id {
794 return Ok((version.to_string(), boot_id.to_string()));
795 }
796 }
797 }
798 }
799 Ok((status, _)) => {
800 last_error = Some(format!("HTTP {status} while waiting for reload"));
801 }
802 Err(e) => {
803 last_error = Some(e);
804 }
805 }
806 std::thread::sleep(RELOAD_POLL_INTERVAL);
807 }
808 match last_error {
809 Some(e) => Err(format!(
810 "surface {} did not come back after reload within {}s ({e})",
811 entry.name,
812 timeout.as_secs()
813 )),
814 None => Err(format!(
815 "surface {} did not report a new boot_id after reload within {}s",
816 entry.name,
817 timeout.as_secs()
818 )),
819 }
820}
821
822fn select_reload_targets(
823 dir: &Path,
824 cwd: &Path,
825 target: Option<&str>,
826 all: bool,
827 err: &mut dyn Write,
828) -> Result<Vec<RegistryEntry>, String> {
829 let listing = live_entries(dir)?;
830 report_unreadable(&listing.unreadable, err);
831 let mut entries = listing.entries;
832 entries.sort_by(|a, b| {
833 a.name
834 .cmp(&b.name)
835 .then_with(|| a.started_at.cmp(&b.started_at))
836 });
837
838 if all {
839 return Ok(entries);
840 }
841
842 if let Some(name_or_id) = target {
843 let matches: Vec<RegistryEntry> = entries
844 .iter()
845 .filter(|e| e.id == name_or_id || e.name == name_or_id)
846 .cloned()
847 .collect();
848 return match matches.len() {
849 0 => {
850 if entries.is_empty() {
851 Err(format!(
852 "no running surface named {name_or_id} (no surfaces are running)"
853 ))
854 } else {
855 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
856 Err(format!(
857 "no running surface named {name_or_id}; running surfaces: {}",
858 names.join(", ")
859 ))
860 }
861 }
862 1 => Ok(matches),
863 _ => {
864 let ids: Vec<&str> = matches.iter().map(|e| e.id.as_str()).collect();
865 Err(format!(
866 "more than one running surface is named {name_or_id}; specify by id: {}",
867 ids.join(", ")
868 ))
869 }
870 };
871 }
872
873 let root = crate::serve::resolve_folder(cwd)?;
874 let matches: Vec<RegistryEntry> = entries.into_iter().filter(|e| e.root == root).collect();
875 match matches.len() {
876 0 => Err(format!("no running surface for {}", root.display())),
877 1 => Ok(matches),
878 _ => {
879 let names: Vec<String> = matches
880 .iter()
881 .map(|e| format!("{} ({})", e.name, e.id))
882 .collect();
883 Err(format!(
884 "multiple surfaces are running for {}; specify one by name or id: {}",
885 root.display(),
886 names.join(", ")
887 ))
888 }
889 }
890}
891
892pub fn run_reload(
893 dir: &Path,
894 cwd: &Path,
895 target: Option<&str>,
896 all: bool,
897 out: &mut dyn Write,
898 err: &mut dyn Write,
899) -> i32 {
900 let targets = match select_reload_targets(dir, cwd, target, all, err) {
901 Ok(targets) => targets,
902 Err(e) => {
903 let _ = writeln!(err, "blyte: {e}");
904 return 1;
905 }
906 };
907
908 if targets.is_empty() {
909 let _ = writeln!(out, "blyte: no surfaces are running");
910 return 0;
911 }
912
913 let mut had_error = false;
914 let mut pending: Vec<(RegistryEntry, String)> = Vec::new();
915 for entry in targets {
916 let token = match read_surface_token(&entry) {
917 Ok(token) => token,
918 Err(e) => {
919 let _ = writeln!(err, "blyte: {e}");
920 had_error = true;
921 continue;
922 }
923 };
924 if let Err(e) = request_reload(&entry, &token) {
925 let _ = writeln!(err, "blyte: {e}");
926 had_error = true;
927 continue;
928 }
929 pending.push((entry, token));
930 }
931
932 for (entry, token) in pending {
933 match wait_for_reloaded_surface(&entry, &token, RELOAD_WAIT_TIMEOUT) {
934 Ok((new_version, _new_boot_id)) => {
935 if !new_version.is_empty() && new_version != entry.runtime.version {
936 let _ = writeln!(
937 out,
938 "blyte: reloaded surface {} ({} -> {})",
939 entry.name, entry.runtime.version, new_version
940 );
941 } else {
942 let version_label = if new_version.is_empty() {
943 entry.runtime.version.as_str()
944 } else {
945 new_version.as_str()
946 };
947 let _ = writeln!(
948 out,
949 "blyte: reloaded surface {} ({version_label})",
950 entry.name
951 );
952 }
953 }
954 Err(e) => {
955 let _ = writeln!(err, "blyte: {e}");
956 had_error = true;
957 }
958 }
959 }
960
961 if had_error {
962 1
963 } else {
964 0
965 }
966}
967
968#[cfg(test)]
969mod tests {
970 use super::count_running_runs_at;
971 use std::time::{Duration, UNIX_EPOCH};
972
973 #[test]
974 fn count_running_runs_at_rejects_pre_epoch_time() {
975 let tmp = tempfile::tempdir().expect("tempdir");
976 std::fs::create_dir_all(tmp.path().join(".git")).expect("create .git");
977 let pre_epoch = UNIX_EPOCH
978 .checked_sub(Duration::from_secs(1))
979 .expect("pre-epoch SystemTime");
980
981 let err = count_running_runs_at(tmp.path(), pre_epoch)
982 .expect_err("expected error for system clock before UNIX_EPOCH");
983 assert!(
984 err.contains("UNIX_EPOCH"),
985 "error should name UNIX_EPOCH: {err}"
986 );
987 }
988}