blyte_cli/
surface_notify.rs1use serde::Deserialize;
2use std::io::{ErrorKind, Read, Write};
3use std::net::{SocketAddr, TcpStream};
4use std::path::Path;
5use std::time::{Duration, Instant};
6
7use crate::serve::TOKEN_HEADER;
8
9const NOTIFY_TIMEOUT: Duration = Duration::from_secs(2);
10const MAX_RESPONSE_HEAD_BYTES: usize = 16 * 1024;
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum NotifyOutcome {
14 NoSurface,
15 Told,
16 Failed(String),
17}
18
19#[derive(Deserialize)]
20struct SurfaceInfo {
21 port: u16,
22}
23
24fn format_notify_failure(port: u16, id: &str, reason: &str) -> NotifyOutcome {
25 NotifyOutcome::Failed(format!(
26 "could not tell the surface at 127.0.0.1:{port} that {id} finished: {reason}; it checks again within 30 s"
27 ))
28}
29
30fn parse_status_code(head_bytes: &[u8]) -> Result<u16, String> {
31 let text = std::str::from_utf8(head_bytes)
32 .map_err(|_| "response status line is not valid UTF-8".to_string())?;
33 let status_line = text.split('\n').next().unwrap_or("").trim_end_matches('\r');
34 let mut parts = status_line.split_whitespace();
35 let version = parts
36 .next()
37 .ok_or_else(|| "empty HTTP response".to_string())?;
38 if !version.starts_with("HTTP/") {
39 return Err("invalid HTTP response".to_string());
40 }
41 let code_str = parts
42 .next()
43 .ok_or_else(|| "missing HTTP status code".to_string())?;
44 code_str
45 .parse::<u16>()
46 .map_err(|_| "invalid HTTP status code".to_string())
47}
48
49fn post_runs_changed(port: u16, token: &str) -> Result<u16, String> {
50 let deadline = Instant::now() + NOTIFY_TIMEOUT;
51 let addr = SocketAddr::from(([127, 0, 0, 1], port));
52 let mut stream = TcpStream::connect_timeout(&addr, NOTIFY_TIMEOUT)
53 .map_err(|e| format!("connection failed: {e}"))?;
54
55 let remaining = deadline.saturating_duration_since(Instant::now());
56 if remaining.is_zero() {
57 return Err("timed out".to_string());
58 }
59 let _ = stream.set_write_timeout(Some(remaining));
60
61 let req = format!(
62 "POST /api/runs/changed HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
63 );
64 stream
65 .write_all(req.as_bytes())
66 .map_err(|e| format!("write failed: {e}"))?;
67
68 let mut raw = Vec::new();
69 let mut chunk = [0u8; 1024];
70 loop {
71 if raw.contains(&b'\n') {
72 break;
73 }
74 if raw.len() >= MAX_RESPONSE_HEAD_BYTES {
75 return Err("response status line too long".to_string());
76 }
77 let remaining = deadline.saturating_duration_since(Instant::now());
78 if remaining.is_zero() {
79 return Err("timed out".to_string());
80 }
81 let _ = stream.set_read_timeout(Some(remaining));
82 match stream.read(&mut chunk) {
83 Ok(0) => break,
84 Ok(n) => raw.extend_from_slice(&chunk[..n]),
85 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
86 Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
87 return Err("timed out".to_string());
88 }
89 Err(e) => return Err(format!("read failed: {e}")),
90 }
91 }
92
93 parse_status_code(&raw)
94}
95
96pub fn notify_runs_changed(main_checkout: &Path, id: &str) -> NotifyOutcome {
97 let wt_dir = main_checkout.join(".wt");
98 let surface_path = wt_dir.join("surface.json");
99 let token_path = wt_dir.join("surface.token");
100
101 let surface_raw = match std::fs::read_to_string(&surface_path) {
102 Ok(s) => s,
103 Err(e) if e.kind() == ErrorKind::NotFound => return NotifyOutcome::NoSurface,
104 Err(e) => {
105 return NotifyOutcome::Failed(format!("cannot read {}: {e}", surface_path.display()));
106 }
107 };
108 let info: SurfaceInfo = match serde_json::from_str(&surface_raw) {
109 Ok(v) => v,
110 Err(e) => {
111 return NotifyOutcome::Failed(format!("cannot parse {}: {e}", surface_path.display()));
112 }
113 };
114
115 let token_raw = match std::fs::read_to_string(&token_path) {
116 Ok(s) => s,
117 Err(e) if e.kind() == ErrorKind::NotFound => return NotifyOutcome::NoSurface,
118 Err(e) => {
119 return NotifyOutcome::Failed(format!("cannot read {}: {e}", token_path.display()));
120 }
121 };
122 let token = token_raw.trim();
123 if token.is_empty() {
124 return NotifyOutcome::Failed(format!("{} is empty", token_path.display()));
125 }
126 if token.contains(['\r', '\n']) {
127 return NotifyOutcome::Failed(format!("invalid token in {}", token_path.display()));
128 }
129
130 match post_runs_changed(info.port, token) {
131 Ok(202) => NotifyOutcome::Told,
132 Ok(status) => {
133 format_notify_failure(info.port, id, &format!("unexpected HTTP status {status}"))
134 }
135 Err(reason) => format_notify_failure(info.port, id, &reason),
136 }
137}
138
139pub fn report(outcome: &NotifyOutcome, err: &mut dyn Write) {
140 if let NotifyOutcome::Failed(msg) = outcome {
141 let _ = writeln!(err, "blyte: {msg}");
142 }
143}