|
| 1 | +//! Configurable transport-reconnect hook. |
| 2 | +//! |
| 3 | +//! When the build-time env var `BUZZ_BUILD_RELAY_RECONNECT_CMD` is set (internal |
| 4 | +//! builds), this command runs an ordered sequence of subprocess steps followed by |
| 5 | +//! a readiness poll before the frontend fires the relay WebSocket reconnect. |
| 6 | +//! |
| 7 | +//! OSS builds (env var unset) get a pure no-op — zero WARP knowledge compiled in. |
| 8 | +
|
| 9 | +// Single source of truth for the config schema, shared with build.rs via |
| 10 | +// `include!`. See reconnect_hook_config.rs for why this is shared, not a module. |
| 11 | +include!("reconnect_hook_config.rs"); |
| 12 | + |
| 13 | +#[tauri::command] |
| 14 | +pub async fn relay_reconnect_hook() -> Result<(), String> { |
| 15 | + let Some(config_str) = option_env!("BUZZ_DESKTOP_BUILD_RELAY_RECONNECT_CMD") else { |
| 16 | + return Ok(()); // OSS build — no-op |
| 17 | + }; |
| 18 | + |
| 19 | + // Safe: build.rs already validated this parses correctly against the same schema. |
| 20 | + let config: ReconnectHookConfig = serde_json::from_str(config_str) |
| 21 | + .map_err(|e| format!("reconnect hook config parse error: {e}"))?; |
| 22 | + |
| 23 | + // spawn_blocking because the desktop Tauri crate doesn't enable tokio's |
| 24 | + // `process` feature; std::process::Command + thread::sleep are synchronous |
| 25 | + // and must not run on an async worker. The whole hook is non-fatal — a join |
| 26 | + // failure logs and returns Ok so the frontend's relay reconnect still fires. |
| 27 | + if let Err(e) = tokio::task::spawn_blocking(move || run_hook(&config)).await { |
| 28 | + eprintln!("[relay_reconnect_hook] task join failed: {e}"); |
| 29 | + } |
| 30 | + |
| 31 | + Ok(()) |
| 32 | +} |
| 33 | + |
| 34 | +/// Run a fixed-argv command (`argv[0]` + `argv[1..]`) with a wall-clock cap. |
| 35 | +/// |
| 36 | +/// `std::process::Command::output()` blocks until the child exits — a wedged |
| 37 | +/// `warp-cli` (the exact degraded-transport case this hook targets) would hang |
| 38 | +/// forever, pinning the blocking-pool thread and leaving the frontend `invoke` |
| 39 | +/// unresolved. So we spawn, poll `try_wait()` every 500ms, and kill+reap on the |
| 40 | +/// deadline. Modeled on `media_transcode.rs` `run_ffmpeg_with_timeout`. |
| 41 | +/// |
| 42 | +/// stdout/stderr are piped and read only after the child exits. The pipe-buffer |
| 43 | +/// deadlock noted there (a child blocking on write() when the ~64 KiB OS pipe |
| 44 | +/// fills) does not apply: `warp-cli` emits a few lines, far below the buffer. |
| 45 | +fn run_with_timeout( |
| 46 | + argv: &[String], |
| 47 | + timeout: std::time::Duration, |
| 48 | +) -> Result<std::process::Output, String> { |
| 49 | + let mut child = std::process::Command::new(&argv[0]) |
| 50 | + .args(&argv[1..]) |
| 51 | + .stdout(std::process::Stdio::piped()) |
| 52 | + .stderr(std::process::Stdio::null()) |
| 53 | + .spawn() |
| 54 | + .map_err(|e| format!("spawn failed: {e}"))?; |
| 55 | + |
| 56 | + let deadline = std::time::Instant::now() + timeout; |
| 57 | + loop { |
| 58 | + match child.try_wait() { |
| 59 | + Ok(Some(status)) => { |
| 60 | + let stdout = child.stdout.take().map_or_else(Vec::new, |mut s| { |
| 61 | + let mut buf = Vec::new(); |
| 62 | + let _ = std::io::Read::read_to_end(&mut s, &mut buf); |
| 63 | + buf |
| 64 | + }); |
| 65 | + return Ok(std::process::Output { |
| 66 | + status, |
| 67 | + stdout, |
| 68 | + stderr: Vec::new(), |
| 69 | + }); |
| 70 | + } |
| 71 | + Ok(None) => { |
| 72 | + if std::time::Instant::now() > deadline { |
| 73 | + let _ = child.kill(); |
| 74 | + let _ = child.wait(); // reap zombie |
| 75 | + return Err(format!("timed out after {}ms", timeout.as_millis())); |
| 76 | + } |
| 77 | + std::thread::sleep(std::time::Duration::from_millis(500)); |
| 78 | + } |
| 79 | + Err(e) => return Err(format!("wait failed: {e}")), |
| 80 | + } |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +/// Runs the configured steps then polls the readiness probe. Every failure is |
| 85 | +/// logged and swallowed — the caller treats the hook as best-effort. |
| 86 | +fn run_hook(config: &ReconnectHookConfig) { |
| 87 | + let cap = std::time::Duration::from_millis(config.timeout_ms); |
| 88 | + |
| 89 | + // Run each step sequentially (fixed-argv, no shell). Each step is capped at |
| 90 | + // `timeout_ms` so a hung child can't stall the whole hook — on cap it's |
| 91 | + // killed, logged, and we move on, same non-fatal contract as a spawn error. |
| 92 | + for step in &config.steps { |
| 93 | + if step.is_empty() { |
| 94 | + continue; |
| 95 | + } |
| 96 | + match run_with_timeout(step, cap) { |
| 97 | + Ok(o) if !o.status.success() => { |
| 98 | + eprintln!("[relay_reconnect_hook] step {:?} exited {}", step, o.status); |
| 99 | + } |
| 100 | + Err(e) => { |
| 101 | + eprintln!("[relay_reconnect_hook] step {:?} failed: {e}", step); |
| 102 | + } |
| 103 | + _ => {} |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + // Poll readiness probe until match or timeout. |
| 108 | + if config.ready_probe.is_empty() { |
| 109 | + return; |
| 110 | + } |
| 111 | + let deadline = std::time::Instant::now() + cap; |
| 112 | + while std::time::Instant::now() < deadline { |
| 113 | + // Cap each probe at the time left to the deadline, so one wedged probe |
| 114 | + // can't push the total probe phase past `timeout_ms`. |
| 115 | + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); |
| 116 | + match run_with_timeout(&config.ready_probe, remaining) { |
| 117 | + Ok(output) if String::from_utf8_lossy(&output.stdout).contains(&config.ready_match) => { |
| 118 | + return; |
| 119 | + } |
| 120 | + Err(e) => { |
| 121 | + eprintln!("[relay_reconnect_hook] probe failed: {e}"); |
| 122 | + } |
| 123 | + _ => {} |
| 124 | + } |
| 125 | + std::thread::sleep(std::time::Duration::from_secs(1)); |
| 126 | + } |
| 127 | +} |
0 commit comments