Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/crates/hive-feed/src/bin/hive-publish.rs # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / crates / hive-feed / src / bin / hive-publish.rs` 283 lines ยท 9754 bytes Raw Blame History 1 //! Sends only already-filtered snapshots through a forced-command SSH key. 2 //! 3 //! A local write is not delivery. The sequence is marked sent only after the 4 //! write finishes, the child is still running, and stderr has no refusal. 5 //! A write that does not finish within five seconds, a child that exits, or 6 //! a refusal tears the session down and the next session sends the snapshot 7 //! again. That is what stops a hung or refusing receiver from freezing 8 //! publication until the service is restarted. 9 10 use std::fs; 11 use std::io::{BufRead, BufReader, Write}; 12 use std::path::Path; 13 use std::process::{Child, ChildStdin, Command, Stdio}; 14 use std::sync::mpsc::{self, Sender}; 15 use std::sync::{Arc, Mutex}; 16 use std::thread; 17 use std::time::{Duration, Instant}; 18 19 const WRITE_DEADLINE: Duration = Duration::from_secs(5); 20 const SURVIVE_GRACE: Duration = Duration::from_millis(200); 21 const HEARTBEAT: Duration = Duration::from_secs(30); 22 const RETRY: Duration = Duration::from_secs(3); 23 24 fn refusal(text: &str) -> bool { 25 text.contains("Hive receiver refused request") || text.contains("Hive receiver rejected snapshot") 26 } 27 28 /// Delivery requires a finished write, a child that is still running, and no refusal. 29 fn delivered(write_finished: bool, child_running: bool, refused: bool) -> bool { 30 write_finished && child_running && !refused 31 } 32 33 fn connect(host: &str, user: &str, identity: &str, known_hosts: &str) -> std::io::Result { 34 Command::new("ssh") 35 .args([ 36 "-F", "/dev/null", 37 "-T", 38 "-i", 39 identity, 40 "-o", 41 "BatchMode=yes", 42 "-o", 43 "IdentitiesOnly=yes", 44 "-o", 45 "StrictHostKeyChecking=yes", 46 "-o", 47 "ClearAllForwardings=yes", 48 "-o", 49 "ConnectTimeout=10", 50 "-o", 51 "ServerAliveInterval=10", 52 "-o", 53 "ServerAliveCountMax=2", 54 "-o", 55 "LogLevel=ERROR", 56 "-o", 57 &format!("UserKnownHostsFile={known_hosts}"), 58 "-l", 59 user, 60 host, 61 "hive-feed", 62 ]) 63 .stdin(Stdio::piped()) 64 .stdout(Stdio::null()) 65 .stderr(Stdio::piped()) 66 .spawn() 67 } 68 69 type WriteAnswer = Sender>; 70 type WriteJob = Option<(Vec, WriteAnswer)>; 71 72 struct Writer { 73 tx: Sender, 74 } 75 76 impl Writer { 77 fn spawn(stdin: ChildStdin) -> Self { 78 let (tx, rx) = mpsc::channel::(); 79 thread::spawn(move || { 80 let mut stdin = stdin; 81 while let Ok(Some((line, reply))) = rx.recv() { 82 let result = stdin.write_all(&line).and_then(|_| stdin.flush()); 83 let _ = reply.send(result); 84 } 85 }); 86 Writer { tx } 87 } 88 89 fn write(&self, line: Vec, deadline: Duration) -> std::io::Result<()> { 90 let (tx, rx) = mpsc::channel(); 91 self.tx 92 .send(Some((line, tx))) 93 .map_err(|_| std::io::Error::other("writer gone"))?; 94 match rx.recv_timeout(deadline) { 95 Ok(result) => result, 96 Err(mpsc::RecvTimeoutError::Timeout) => { 97 Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "publish write stalled")) 98 } 99 Err(mpsc::RecvTimeoutError::Disconnected) => { 100 Err(std::io::Error::other("writer dropped the write")) 101 } 102 } 103 } 104 } 105 106 fn spawn_stderr(child: &mut Child) -> std::io::Result<(thread::JoinHandle<()>, Arc>)> { 107 let stderr = child.stderr.take().ok_or_else(|| std::io::Error::other("stderr was not piped"))?; 108 let buf = Arc::new(Mutex::new(String::new())); 109 let share = Arc::clone(&buf); 110 let handle = thread::spawn(move || { 111 let mut reader = BufReader::new(stderr); 112 let mut line = String::new(); 113 loop { 114 line.clear(); 115 match reader.read_line(&mut line) { 116 Ok(0) => break, 117 Ok(_) => { 118 let mut guard = share.lock().unwrap_or_else(|poison| poison.into_inner()); 119 if guard.len() < 4096 { 120 guard.push_str(&line); 121 } 122 } 123 Err(_) => break, 124 } 125 } 126 }); 127 Ok((handle, buf)) 128 } 129 130 fn child_running(child: &mut Child) -> bool { 131 matches!(child.try_wait(), Ok(None)) 132 } 133 134 fn survived(child: &mut Child, grace: Duration) -> bool { 135 let start = Instant::now(); 136 loop { 137 if !child_running(child) { 138 return false; 139 } 140 if start.elapsed() >= grace { 141 return true; 142 } 143 thread::sleep(Duration::from_millis(20)); 144 } 145 } 146 147 fn notes_of(buf: &Mutex) -> String { 148 buf.lock().unwrap_or_else(|poison| poison.into_inner()).clone() 149 } 150 151 fn snapshot_line(path: &Path) -> Option<(String, Vec)> { 152 let meta = fs::metadata(path).ok()?; 153 if meta.len() > 2 * 1024 * 1024 { 154 return None; 155 } 156 let bytes = fs::read(path).ok()?; 157 let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?; 158 let sequence = value.get("sequence")?.as_str()?.to_string(); 159 if sequence.is_empty() { 160 return None; 161 } 162 let mut line = serde_json::to_vec(&value).expect("JSON value serializes"); 163 line.push(b'\n'); 164 Some((sequence, line)) 165 } 166 167 /// One SSH session. Returns when the session must be torn down and retried. 168 fn run_session(ssh: &mut Child, writer: &Writer, stderr_buf: &Mutex, path: &Path) { 169 let mut sent = String::new(); 170 let mut last_beat = Instant::now(); 171 loop { 172 if !child_running(ssh) { 173 eprintln!("Hive transport interrupted; retrying"); 174 return; 175 } 176 if refusal(¬es_of(stderr_buf)) { 177 eprintln!("hive-publish: receiver refused snapshot; reconnecting"); 178 return; 179 } 180 if last_beat.elapsed() >= HEARTBEAT { 181 let shown = if sent.is_empty() { "(none)" } else { sent.as_str() }; 182 eprintln!("hive-publish: transport up, last sequence {shown}"); 183 last_beat = Instant::now(); 184 } 185 if let Some((sequence, line)) = snapshot_line(path) { 186 if sequence != sent { 187 match writer.write(line, WRITE_DEADLINE) { 188 Ok(()) => { 189 let refused = refusal(¬es_of(stderr_buf)); 190 let running = survived(ssh, SURVIVE_GRACE); 191 if delivered(true, running, refused) { 192 sent = sequence; 193 eprintln!("hive-publish: sent sequence {sent}"); 194 } else if refused { 195 eprintln!("hive-publish: receiver refused snapshot; reconnecting"); 196 return; 197 } else { 198 eprintln!("Hive transport interrupted; retrying"); 199 return; 200 } 201 } 202 Err(error) if error.kind() == std::io::ErrorKind::TimedOut => { 203 eprintln!("hive-publish: write stalled; reconnecting"); 204 return; 205 } 206 Err(_) => { 207 eprintln!("Hive transport interrupted; retrying"); 208 return; 209 } 210 } 211 } 212 } 213 thread::sleep(Duration::from_millis(200)); 214 } 215 } 216 217 fn main() { 218 let args: Vec = std::env::args().collect(); 219 if args.len() != 6 || args[2].starts_with('-') || args[3].starts_with('-') { 220 eprintln!("Usage: hive-publish SNAPSHOT HOST USER IDENTITY KNOWN_HOSTS"); 221 std::process::exit(2); 222 } 223 let path = Path::new(&args[1]); 224 loop { 225 let mut ssh = match connect(&args[2], &args[3], &args[4], &args[5]) { 226 Ok(child) => child, 227 Err(_) => { 228 eprintln!("Hive transport unavailable; retrying"); 229 thread::sleep(RETRY); 230 continue; 231 } 232 }; 233 let stdin = match ssh.stdin.take() { 234 Some(stdin) => stdin, 235 None => { 236 let _ = ssh.kill(); 237 let _ = ssh.wait(); 238 eprintln!("Hive transport interrupted; retrying"); 239 thread::sleep(RETRY); 240 continue; 241 } 242 }; 243 let writer = Writer::spawn(stdin); 244 let (stderr_thread, stderr_buf) = match spawn_stderr(&mut ssh) { 245 Ok(pair) => pair, 246 Err(_) => { 247 let _ = ssh.kill(); 248 let _ = ssh.wait(); 249 eprintln!("Hive transport interrupted; retrying"); 250 thread::sleep(RETRY); 251 continue; 252 } 253 }; 254 run_session(&mut ssh, &writer, &stderr_buf, path); 255 // Kill before dropping the writer so a blocked write unblocks. 256 let _ = ssh.kill(); 257 let _ = ssh.wait(); 258 drop(writer); 259 let _ = stderr_thread.join(); 260 thread::sleep(RETRY); 261 } 262 } 263 264 #[cfg(test)] 265 mod tests { 266 use super::*; 267 268 #[test] 269 fn refusal_matches_only_receiver_lines() { 270 assert!(refusal("Hive receiver refused request\n")); 271 assert!(refusal("prefix Hive receiver rejected snapshot\n")); 272 assert!(!refusal("hive-publish: sent sequence abc")); 273 assert!(!refusal("")); 274 } 275 276 #[test] 277 fn delivery_requires_a_live_child_and_no_refusal() { 278 assert!(delivered(true, true, false)); 279 assert!(!delivered(false, true, false)); 280 assert!(!delivered(true, false, false)); 281 assert!(!delivered(true, true, true)); 282 } 283 }