← Commit history

0.2.94: keep serving when tiny_http's accept loop stops; self-check ticker (#30)

Colby Knox ·ed6e3ecd3b · ·parent 2fea2a7
7 files changed +109−7
CHANGELOG.md+7
@@ -1,5 +1,12 @@ # Changelog +## 0.2.94++- **The bridge no longer exits when its HTTP listener stops accepting** (#30). On one machine every bridge process stopped 30 to 60 s after it started, with nothing printed. 0.2.93's crash log already captures Rust's own fatal messages, so this was not a stack overflow or a failed allocation. tiny_http 0.12 ends its accept thread on the first failed `accept()`, after which the bridge's request loop ended and the process exited cleanly and silently. The bridge now logs the error to `altium-bridge-crash.log` and listens again on the same port.+- **A self-check every few seconds.** The bridge asks its own port for `/ping` every 5 s for its first 5 minutes, then every minute, and records it in `altium-bridge-trace.log`. When it stops answering, the reason (connect, read, no reply) goes to `altium-bridge-crash.log` with the pid. This tells "alive but not answering" apart from "gone", which nothing could before.+- New `GET /ping`: answers at once with the pid. The self-check uses it.+- Tested on Altium Designer 26.11.1 (Windows 11): the self-check answered in under 1 ms on every tick. Bursts of thousands of connections reset before they could be accepted did not stop the bridge on the test machine. The lifecycle battery passed 13 of 13.+ ## 0.2.93  - **`engineParked` sees a parked agent whatever document is in front** (#30, reported by Ivan Mendez). It used to require the agent's own script to be the document in front. On Ivan's machine the parked script sat behind the user's schematic, so `check_dialogs`, `readiness` and `agent_status` all said `engineParked: false` while Altium refused to exit. The bridge now reads the agent's own files: a loop that started in the running Altium and neither exited nor heartbeat for 15 s is parked.
bridge-rs/src/main.rs+36−3
@@ -80,7 +80,7 @@ use tiny_http::{Header, Method, Response, Server}; /// Attached to every failed reply (see the /command handler). const REPORT_ISSUES: &str = "If this looks like an altium-bridge BUG (not a refusal you expected), report it: check for a duplicate with `adom-wiki issue list adom/altium-bridge`, then `adom-wiki issue create adom/altium-bridge --title \"<verb>: <one-line symptom>\" --category bug-report --body \"<what you ran, what you expected, what happened, the VERBATIM response JSON (and errorShot if present), bridgeVersion, the Altium version from altium_status, the OS>\"`. A relay, routing, toast or lifecycle problem belongs on adom/adom-bridge instead. Reports from real machines are how this bridge gets correct: three different Altium builds behaved three different ways in one weekend."; -pub const BRIDGE_VERSION: &str = "0.2.93";+pub const BRIDGE_VERSION: &str = "0.2.94";  fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> {     let data = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());@@ -144,8 +144,9 @@ fn main() {         .and_then(|p| p.parse().ok())         .unwrap_or(0);     let host = std::env::var("ADOM_BIND_HOST").unwrap_or_else(|_| "127.0.0.1".into());-    let server = Server::http(format!("{host}:{port}")).expect("bind");+    let mut server = Server::http(format!("{host}:{port}")).expect("bind");     let bound = server.server_addr();+    let bound_ip = bound.clone().to_ip();     println!("[altium] bridge {BRIDGE_VERSION} listening on {bound}");     install_crash_log();     trace::step(&format!("bridge {BRIDGE_VERSION} started, listening on {bound}"));@@ -161,7 +162,38 @@ fn main() {     // bridge kept grinding the abandoned request, and the queue only grew (the 30-verb cascades the     // verb battery found, 2026-09-20). Agent-bound work still serialises where it must: the agent's     // one-file inbox, which now answers a NAMED agent_busy instead of a dropped connection.-    for mut req in server.incoming_requests() {+    if let Some(addr) = bound_ip {+        trace::start_ticker(addr);+    }+    // NOT `for req in server.incoming_requests()`: tiny_http 0.12 ends its accept thread on the first failed accept and+    // the iterator then ends, so main returned and the bridge exited with no message at all. Log it and listen again+    // on the same port (#30).+    loop {+        let mut req = match server.recv() {+            Ok(r) => r,+            Err(e) => {+                let msg = format!("the HTTP listener stopped accepting: {e} (kind {:?}); listening again on {bound}", e.kind());+                trace::step(&msg);+                append_crash_log(&format!("[{}] {msg}\n", stamp()));+                drop(server);+                let mut again = None;+                for _ in 0..50 {+                    match bound_ip.map(Server::http) {+                        Some(Ok(s)) => { again = Some(s); break; }+                        _ => std::thread::sleep(std::time::Duration::from_millis(200)),+                    }+                }+                match again {+                    Some(s) => { trace::step("listening again"); server = s; continue; }+                    None => {+                        let msg = format!("could not listen again on {bound}: the bridge exits so ab starts a fresh one");+                        trace::step(&msg);+                        append_crash_log(&format!("[{}] {msg}\n", stamp()));+                        std::process::exit(3);+                    }+                }+            }+        };         // 16 MB, not the 2 MB default: a request runs Altium's whole lifecycle (start, recover, their checks) on its own         // thread, and a stack overflow ends the PROCESS with no log at all (adom/altium-bridge#30)         let spawned = std::thread::Builder::new().name("altium-request".into()).stack_size(16 << 20).spawn(move || {@@ -170,6 +202,7 @@ fn main() {         let method = req.method().clone();         let resp = match (method, path.as_str()) {             (Method::Get, "/health") | (Method::Get, "/status") => json_response(200, &health::report()),+            (Method::Get, "/ping") => json_response(200, &serde_json::json!({"ok": true, "pid": std::process::id()})),             (Method::Get, "/verbs") => json_response(200, &serde_json::json!({"verbs": verbs::names(), "bridgeVersion": BRIDGE_VERSION})),             (Method::Post, "/command") => {                 let mut body = String::new();
bridge-rs/src/trace.rs+62
@@ -103,6 +103,24 @@ pub fn previous_run_report() -> Option<String> { mod tests {     use super::unfinished; +    #[test]+    fn self_probe_tells_answering_from_deaf() {+        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();+        let addr = server.server_addr().to_ip().unwrap();+        let t = std::thread::spawn(move || {+            let rq = server.recv().unwrap();+            let _ = rq.respond(tiny_http::Response::from_string("{}"));+            // the listener is dropped here, as when tiny_http's accept thread ends+        });+        assert!(super::self_probe(addr).is_ok());+        t.join().unwrap();+        std::thread::sleep(std::time::Duration::from_millis(200));+        let e = super::self_probe(addr).unwrap_err();+        assert!(e.starts_with("connect") || e.starts_with("read") || e.starts_with("no HTTP"), "{e}");+        // and the same port can be listened on again (main does this when the accept loop stops)+        assert!(tiny_http::Server::http(addr).is_ok());+    }+     #[test]     fn names_the_request_the_last_process_died_in() {         let t = "1 pid=10 thread=a:ThreadId(2) heal=0 sp=0x1 BEGIN #1 altium_status\n\@@ -118,3 +136,47 @@ mod tests {         assert!(unfinished("1 pid=99 thread=a heal=0 sp=0x1 BEGIN #1 x\n", 99).is_none());     } }++/// Ask our own port for /ping, the way ab reaches us. `Err` names what failed: a bridge that is alive but no longer+/// answers is a different fault from one that died, and only this can tell them apart from inside (#30).+pub fn self_probe(addr: std::net::SocketAddr) -> Result<u128, String> {+    use std::io::Read;+    use std::time::Duration;+    let t0 = std::time::Instant::now();+    let mut s = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(3)).map_err(|e| format!("connect: {e}"))?;+    let _ = s.set_read_timeout(Some(Duration::from_secs(5)));+    let _ = s.set_write_timeout(Some(Duration::from_secs(3)));+    s.write_all(b"GET /ping HTTP/1.0\r\nHost: localhost\r\n\r\n").map_err(|e| format!("write: {e}"))?;+    let mut buf = [0u8; 64];+    let n = s.read(&mut buf).map_err(|e| format!("read: {e}"))?;+    if n == 0 || !buf[..n].starts_with(b"HTTP/1.") { return Err(format!("no HTTP answer ({n} bytes)")); }+    Ok(t0.elapsed().as_millis())+}++/// Record that the process is alive, and whether it still answers on its own port: every 5 s for the first 5 minutes+/// (one machine lost its bridge 30 to 60 s after every start), then every minute. A failed probe is always written.+pub fn start_ticker(addr: std::net::SocketAddr) {+    let _ = std::thread::Builder::new().name("altium-trace-ticker".into()).spawn(move || {+        let born = std::time::Instant::now();+        let mut last_written = std::time::Instant::now();+        loop {+            let early = born.elapsed() < std::time::Duration::from_secs(300);+            std::thread::sleep(std::time::Duration::from_secs(if early { 5 } else { 60 }));+            let probe = self_probe(addr);+            let due = early || last_written.elapsed() >= std::time::Duration::from_secs(600);+            match probe {+                Ok(ms) if due => { step(&format!("tick {}s: answering on {addr} ({ms} ms)", born.elapsed().as_secs())); last_written = std::time::Instant::now(); }+                Ok(_) => {}+                Err(e) => {+                    let msg = format!("tick {}s: NOT answering on {addr}: {e}", born.elapsed().as_secs());+                    step(&msg);+                    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true)+                        .open(path().with_file_name("altium-bridge-crash.log")) {+                        let _ = f.write_all(format!("[{}] bridge pid {}: {msg}\n", now_ms() / 1000, std::process::id()).as_bytes());+                    }+                    last_written = std::time::Instant::now();+                }+            }+        }+    });+}
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.93",+  "version": "0.2.94",   "type": "app",   "description": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.",   "tags": [
page.json+1−1
@@ -4,7 +4,7 @@   "type": "app",   "title": "Altium Bridge: AI for Altium Designer",   "brief": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.",-  "version": "0.2.93",+  "version": "0.2.94",   "hero": {     "type": "image",     "path": "screenshots/hero.png"
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.93+0.2.94
src/bridge.json+1−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.93",+  "version": "0.2.94",   "description": "Drive Altium Designer from Adom: a resident DelphiScript agent (eval + the 1,100-command process launcher), the X2 -R command line, UIA over the VCL shell, dialogs by PID, screenshots of every Altium window, and Altium 365.",   "homepage": "https://wiki.adom.inc/adom/altium-bridge",   "docs": "https://wiki.adom.inc/adom/altium-bridge",