diff --git a/crates/hive-feed/src/bin/hive-publish.rs b/crates/hive-feed/src/bin/hive-publish.rs index 2170c25..ef48499 100644 --- a/crates/hive-feed/src/bin/hive-publish.rs +++ b/crates/hive-feed/src/bin/hive-publish.rs @@ -1,22 +1,216 @@ //! Sends only already-filtered snapshots through a forced-command SSH key. +//! +//! A local write is not delivery. The sequence is marked sent only after the +//! write finishes, the child is still running, and stderr has no refusal. +//! A write that does not finish within five seconds, a child that exits, or +//! a refusal tears the session down and the next session sends the snapshot +//! again. That is what stops a hung or refusing receiver from freezing +//! publication until the service is restarted. + use std::fs; -use std::io::Write; +use std::io::{BufRead, BufReader, Write}; use std::path::Path; -use std::process::{Child, Command, Stdio}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc::{self, Sender}; +use std::sync::{Arc, Mutex}; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; + +const WRITE_DEADLINE: Duration = Duration::from_secs(5); +const SURVIVE_GRACE: Duration = Duration::from_millis(200); +const HEARTBEAT: Duration = Duration::from_secs(30); +const RETRY: Duration = Duration::from_secs(3); + +fn refusal(text: &str) -> bool { + text.contains("Hive receiver refused request") || text.contains("Hive receiver rejected snapshot") +} + +/// Delivery requires a finished write, a child that is still running, and no refusal. +fn delivered(write_finished: bool, child_running: bool, refused: bool) -> bool { + write_finished && child_running && !refused +} fn connect(host: &str, user: &str, identity: &str, known_hosts: &str) -> std::io::Result { Command::new("ssh") - .args(["-F", "/dev/null", "-T", "-i", identity, - "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", - "-o", "StrictHostKeyChecking=yes", "-o", "ClearAllForwardings=yes", - "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=10", - "-o", "ServerAliveCountMax=2", "-o", "LogLevel=ERROR", - "-o", &format!("UserKnownHostsFile={known_hosts}"), - "-l", user, host, "hive-feed"]) - .stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() + .args([ + "-F", "/dev/null", + "-T", + "-i", + identity, + "-o", + "BatchMode=yes", + "-o", + "IdentitiesOnly=yes", + "-o", + "StrictHostKeyChecking=yes", + "-o", + "ClearAllForwardings=yes", + "-o", + "ConnectTimeout=10", + "-o", + "ServerAliveInterval=10", + "-o", + "ServerAliveCountMax=2", + "-o", + "LogLevel=ERROR", + "-o", + &format!("UserKnownHostsFile={known_hosts}"), + "-l", + user, + host, + "hive-feed", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() +} + +struct Writer { + tx: Sender, Sender>)>>, +} + +impl Writer { + fn spawn(stdin: ChildStdin) -> Self { + let (tx, rx) = mpsc::channel::, Sender>)>>(); + thread::spawn(move || { + let mut stdin = stdin; + while let Ok(Some((line, reply))) = rx.recv() { + let result = stdin.write_all(&line).and_then(|_| stdin.flush()); + let _ = reply.send(result); + } + }); + Writer { tx } + } + + fn write(&self, line: Vec, deadline: Duration) -> std::io::Result<()> { + let (tx, rx) = mpsc::channel(); + self.tx + .send(Some((line, tx))) + .map_err(|_| std::io::Error::other("writer gone"))?; + match rx.recv_timeout(deadline) { + Ok(result) => result, + Err(mpsc::RecvTimeoutError::Timeout) => { + Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "publish write stalled")) + } + Err(mpsc::RecvTimeoutError::Disconnected) => { + Err(std::io::Error::other("writer dropped the write")) + } + } + } +} + +fn spawn_stderr(child: &mut Child) -> std::io::Result<(thread::JoinHandle<()>, Arc>)> { + let stderr = child.stderr.take().ok_or_else(|| std::io::Error::other("stderr was not piped"))?; + let buf = Arc::new(Mutex::new(String::new())); + let share = Arc::clone(&buf); + let handle = thread::spawn(move || { + let mut reader = BufReader::new(stderr); + let mut line = String::new(); + loop { + line.clear(); + match reader.read_line(&mut line) { + Ok(0) => break, + Ok(_) => { + let mut guard = share.lock().unwrap_or_else(|poison| poison.into_inner()); + if guard.len() < 4096 { + guard.push_str(&line); + } + } + Err(_) => break, + } + } + }); + Ok((handle, buf)) +} + +fn child_running(child: &mut Child) -> bool { + matches!(child.try_wait(), Ok(None)) +} + +fn survived(child: &mut Child, grace: Duration) -> bool { + let start = Instant::now(); + loop { + if !child_running(child) { + return false; + } + if start.elapsed() >= grace { + return true; + } + thread::sleep(Duration::from_millis(20)); + } +} + +fn notes_of(buf: &Mutex) -> String { + buf.lock().unwrap_or_else(|poison| poison.into_inner()).clone() } + +fn snapshot_line(path: &Path) -> Option<(String, Vec)> { + let meta = fs::metadata(path).ok()?; + if meta.len() > 2 * 1024 * 1024 { + return None; + } + let bytes = fs::read(path).ok()?; + let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?; + let sequence = value.get("sequence")?.as_str()?.to_string(); + if sequence.is_empty() { + return None; + } + let mut line = serde_json::to_vec(&value).expect("JSON value serializes"); + line.push(b'\n'); + Some((sequence, line)) +} + +/// One SSH session. Returns when the session must be torn down and retried. +fn run_session(ssh: &mut Child, writer: &Writer, stderr_buf: &Mutex, path: &Path) { + let mut sent = String::new(); + let mut last_beat = Instant::now(); + loop { + if !child_running(ssh) { + eprintln!("Hive transport interrupted; retrying"); + return; + } + if refusal(¬es_of(stderr_buf)) { + eprintln!("hive-publish: receiver refused snapshot; reconnecting"); + return; + } + if last_beat.elapsed() >= HEARTBEAT { + let shown = if sent.is_empty() { "(none)" } else { sent.as_str() }; + eprintln!("hive-publish: transport up, last sequence {shown}"); + last_beat = Instant::now(); + } + if let Some((sequence, line)) = snapshot_line(path) { + if sequence != sent { + match writer.write(line, WRITE_DEADLINE) { + Ok(()) => { + let refused = refusal(¬es_of(stderr_buf)); + let running = survived(ssh, SURVIVE_GRACE); + if delivered(true, running, refused) { + sent = sequence; + eprintln!("hive-publish: sent sequence {sent}"); + } else if refused { + eprintln!("hive-publish: receiver refused snapshot; reconnecting"); + return; + } else { + eprintln!("Hive transport interrupted; retrying"); + return; + } + } + Err(error) if error.kind() == std::io::ErrorKind::TimedOut => { + eprintln!("hive-publish: write stalled; reconnecting"); + return; + } + Err(_) => { + eprintln!("Hive transport interrupted; retrying"); + return; + } + } + } + } + thread::sleep(Duration::from_millis(200)); + } +} + fn main() { let args: Vec = std::env::args().collect(); if args.len() != 6 || args[2].starts_with('-') || args[3].starts_with('-') { @@ -27,34 +221,60 @@ fn main() { loop { let mut ssh = match connect(&args[2], &args[3], &args[4], &args[5]) { Ok(child) => child, - Err(_) => { eprintln!("Hive transport unavailable; retrying"); thread::sleep(Duration::from_secs(3)); continue; } + Err(_) => { + eprintln!("Hive transport unavailable; retrying"); + thread::sleep(RETRY); + continue; + } }; - let mut sent = String::new(); - loop { - if !matches!(ssh.try_wait(), Ok(None)) { break; } - if let Ok(meta) = fs::metadata(path) { - if meta.len() <= 2 * 1024 * 1024 { - if let Ok(bytes) = fs::read(path) { - if let Ok(value) = serde_json::from_slice::(&bytes) { - if let Some(sequence) = value.get("sequence").and_then(|v| v.as_str()) { - if sequence != sent { - // Compact to one newline-delimited record; transport never reads raw sources. - let mut line = serde_json::to_vec(&value).expect("JSON value serializes"); - line.push(b'\n'); - if ssh.stdin.as_mut().is_none_or(|input| input.write_all(&line).is_err()) { break; } - sent.clear(); - sent.push_str(sequence); - } - } - } - } - } + let stdin = match ssh.stdin.take() { + Some(stdin) => stdin, + None => { + let _ = ssh.kill(); + let _ = ssh.wait(); + eprintln!("Hive transport interrupted; retrying"); + thread::sleep(RETRY); + continue; } - thread::sleep(Duration::from_millis(200)); - } + }; + let writer = Writer::spawn(stdin); + let (stderr_thread, stderr_buf) = match spawn_stderr(&mut ssh) { + Ok(pair) => pair, + Err(_) => { + let _ = ssh.kill(); + let _ = ssh.wait(); + eprintln!("Hive transport interrupted; retrying"); + thread::sleep(RETRY); + continue; + } + }; + run_session(&mut ssh, &writer, &stderr_buf, path); + // Kill before dropping the writer so a blocked write unblocks. let _ = ssh.kill(); let _ = ssh.wait(); - eprintln!("Hive transport interrupted; retrying"); - thread::sleep(Duration::from_secs(3)); + drop(writer); + let _ = stderr_thread.join(); + thread::sleep(RETRY); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn refusal_matches_only_receiver_lines() { + assert!(refusal("Hive receiver refused request\n")); + assert!(refusal("prefix Hive receiver rejected snapshot\n")); + assert!(!refusal("hive-publish: sent sequence abc")); + assert!(!refusal("")); + } + + #[test] + fn delivery_requires_a_live_child_and_no_refusal() { + assert!(delivered(true, true, false)); + assert!(!delivered(false, true, false)); + assert!(!delivered(true, false, false)); + assert!(!delivered(true, true, true)); } } diff --git a/crates/hive-feed/tests/publish_stall.rs b/crates/hive-feed/tests/publish_stall.rs new file mode 100644 index 0000000..350cfa5 --- /dev/null +++ b/crates/hive-feed/tests/publish_stall.rs @@ -0,0 +1,179 @@ +//! The publisher must not treat a local write as delivery, and a receiver +//! that never reads must not freeze the process. +use std::fs; +use std::io::Read; +use std::process::{Command, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; + +fn bin() -> &'static str { + env!("CARGO_BIN_EXE_hive-publish") +} + +fn write_ssh(dir: &std::path::Path) { + let path = dir.join("ssh"); + fs::write( + &path, + "#!/bin/sh\n\ + echo start >> \"$HIVE_FAKE_LOG\"\n\ + if [ \"$HIVE_FAKE_MODE\" = hang ]; then\n\ + exec sleep 120\n\ + fi\n\ + if [ \"$HIVE_FAKE_MODE\" = refuse ]; then\n\ + echo 'Hive receiver rejected snapshot' >&2\n\ + exit 1\n\ + fi\n\ + if [ \"$HIVE_FAKE_MODE\" = ok ]; then\n\ + exec cat >/dev/null\n\ + fi\n\ + exit 1\n", + ) + .unwrap(); + let mut perm = fs::metadata(&path).unwrap().permissions(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + perm.set_mode(0o755); + } + fs::set_permissions(&path, perm).unwrap(); +} + +fn snapshot(path: &std::path::Path, sequence: &str, pad: usize) { + let body = "x".repeat(pad); + let text = format!("{{\"sequence\":{sequence:?},\"body\":{body:?}}}"); + fs::write(path, text).unwrap(); +} + +struct Publisher { + child: std::process::Child, + dir: std::path::PathBuf, +} + +impl Publisher { + fn start(mode: &str, sequence: &str, pad: usize) -> Self { + let dir = std::env::temp_dir().join(format!( + "aienosqueue-hive-{}-{}", + mode, + std::process::id() + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + write_ssh(&dir); + let snap = dir.join("live.json"); + snapshot(&snap, sequence, pad); + fs::write(dir.join("key"), b"not-a-key").unwrap(); + fs::write(dir.join("known"), b"").unwrap(); + let log = dir.join("ssh.log"); + fs::write(&log, b"").unwrap(); + let mut prefixed = dir.as_os_str().to_owned(); + prefixed.push(":"); + if let Some(path) = std::env::var_os("PATH") { + prefixed.push(path); + } + let child = Command::new(bin()) + .args([ + snap.to_str().unwrap(), + "edge.example", + "hive", + dir.join("key").to_str().unwrap(), + dir.join("known").to_str().unwrap(), + ]) + .env("PATH", prefixed) + .env("HIVE_FAKE_MODE", mode) + .env("HIVE_FAKE_LOG", &log) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + Publisher { child, dir } + } + + fn stops(&mut self) -> String { + let _ = self.child.kill(); + let _ = self.child.wait(); + let mut buf = String::new(); + if let Some(mut err) = self.child.stderr.take() { + let _ = err.read_to_string(&mut buf); + } + buf + } +} + +impl Drop for Publisher { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + let _ = fs::remove_dir_all(&self.dir); + } +} + +fn wait_until(mut pred: impl FnMut() -> bool, limit: Duration) -> bool { + let start = Instant::now(); + while start.elapsed() < limit { + if pred() { + return true; + } + thread::sleep(Duration::from_millis(100)); + } + pred() +} + +#[test] +fn usage_exits_2() { + let status = Command::new(bin()).status().unwrap(); + assert_eq!(status.code(), Some(2)); +} + +#[test] +fn hung_receiver_is_killed_and_retried() { + let mut pub_ = Publisher::start("hang", "seq-hang-1", 80_000); + let log = pub_.dir.join("ssh.log"); + let retried = wait_until( + || fs::read_to_string(&log).unwrap_or_default().matches("start").count() >= 2, + Duration::from_secs(12), + ); + let starts = fs::read_to_string(&log).unwrap_or_default().matches("start").count(); + let err = pub_.stops(); + assert!(retried, "publisher stayed on one hung ssh; log starts={starts}, stderr={err}"); + assert!(err.contains("hive-publish: write stalled; reconnecting"), "{err}"); + assert!(!err.contains("sent sequence"), "a stalled write must not be recorded as sent: {err}"); + assert!(!err.contains("xxxxxxxx"), "snapshot body must not be logged: {err}"); +} + +#[test] +fn refusing_receiver_is_not_recorded_as_sent() { + let mut pub_ = Publisher::start("refuse", "seq-refuse-1", 0); + let log = pub_.dir.join("ssh.log"); + let retried = wait_until( + || fs::read_to_string(&log).unwrap_or_default().matches("start").count() >= 2, + Duration::from_secs(8), + ); + let err = pub_.stops(); + assert!(retried, "publisher did not reconnect after refusal; stderr={err}"); + assert!( + err.contains("receiver refused snapshot") || err.contains("Hive transport interrupted"), + "{err}" + ); + assert!(!err.contains("sent sequence"), "a refusal must not be recorded as sent: {err}"); +} + +#[test] +fn live_receiver_records_one_send_and_stays_up() { + let mut pub_ = Publisher::start("ok", "seq-ok-1", 0); + let log = pub_.dir.join("ssh.log"); + let up = wait_until( + || { + fs::read_to_string(&log).unwrap_or_default().matches("start").count() == 1 + && pub_.child.try_wait().ok().flatten().is_none() + }, + Duration::from_secs(3), + ); + assert!(up, "healthy ssh did not stay up"); + thread::sleep(Duration::from_secs(2)); + let starts = fs::read_to_string(&log).unwrap_or_default().matches("start").count(); + let err = pub_.stops(); + assert_eq!(starts, 1, "a live receiver must not be torn down; stderr={err}"); + assert!(err.contains("hive-publish: sent sequence seq-ok-1"), "{err}"); + assert!(!err.contains("write stalled"), "{err}"); +}