AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(server): first-launch console link prints the bound ES-compat port, not the requested one
Vincenzo Lombardo53ff8eea0c78
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 0cb844b66..46b5f20ef 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -2202,6 +2202,62 @@ async fn async_main() -> Result<()> {None};+ // 8c. Bind all three listeners NOW — before the console setup link, before+ // the banner, before anything reports readiness, and fatally.+ //+ // This used to happen at step 10/10a below, well after the console+ // bootstrap at (old) step 9 had already built and printed its+ // first-launch setup link from `cfg.server.es_compat_port` — the+ // *requested* port, not the one the kernel handed back. With an+ // ephemeral port (`es_compat_port = 0`) that produced+ // `http://127.0.0.1:0/_xerj-console/setup#token=…`, a link the single+ // action a first-run operator is told to take, and unreachable. It+ // also ran ahead of the bind, so it printed to stderr whether or not+ // the bind that follows ever succeeds (issue #469; #466 fixed the+ // same class for the startup banner, printed from `local_addr()`+ // right below).+ //+ // Moving the bind here — ahead of the console bootstrap rather than+ // just ahead of the banner — means both the setup link and the banner+ // can only ever be built from a port this process actually holds; see+ // `bind_listener` for why binding eagerly and fatally is itself+ // load-bearing (issue #465).+ //+ // Addresses are composed from the parsed IP, never by formatting+ // `"{bind}:{port}"` — that string is unparseable for every IPv6+ // literal (`"::1:9200"`), which made `bind_address = "::1"` a node+ // that could not start at all. `socket_addr` cannot be `None` here:+ // step 3a rejected an unparseable `bind_address` before the data+ // directory existed, which is where that failure belongs. The+ // context is kept as a backstop so that if a future edit reorders or+ // drops 3a, this still names the setting rather than surfacing a bare+ // `Option` unwrap.+ let rest_addr: SocketAddr = cfg+ .socket_addr(cfg.server.rest_port)+ .with_context(|| bad_bind_address(&cfg))?;+ let es_addr: SocketAddr = cfg+ .socket_addr(cfg.server.es_compat_port)+ .with_context(|| bad_bind_address(&cfg))?;+ let grpc_addr: SocketAddr = cfg+ .socket_addr(cfg.server.grpc_port)+ .with_context(|| bad_bind_address(&cfg))?;++ let rest_listener = bind_listener(rest_addr, "native REST")?;+ let es_listener = bind_listener(es_addr, "ES-compat")?;+ let grpc_listener = bind_listener(grpc_addr, "gRPC")?;++ let bound = BoundAddrs {+ rest: rest_listener+ .local_addr()+ .context("native REST: read the bound address")?,+ es: es_listener+ .local_addr()+ .context("ES-compat: read the bound address")?,+ grpc: grpc_listener+ .local_addr()+ .context("gRPC: read the bound address")?,+ };+// 9. Xerj Console bootstrap. Creates `.xerj_*` system indices on first// boot, persists a 32-byte master key under data_dir/.xerj_master_key// (mode 0600), and prints the first-launch magic-link banner to@@ -2223,7 +2279,10 @@ async fn async_main() -> Result<()> {// first-launch console link.url_host(&cfg.server.bind_address)},- cfg.server.es_compat_port,+ // The bound ES-compat port (8c), not `cfg.server.es_compat_port`: with+ // an ephemeral port (`= 0`) the config value is never the port the+ // node ends up listening on (issue #469).+ bound.es.port(),);let xerj_console_node_id: String = match (cfg.cluster.enabled, cluster_listen_addr) {// The same string the cluster transport registered as this node's id.@@ -2336,62 +2395,15 @@ async fn async_main() -> Result<()> {es_router = es_router.merge(xerj_console_router);}- // 10. Bind addresses. Composed from the parsed IP, never by formatting- // `"{bind}:{port}"` — that string is unparseable for every IPv6- // literal (`"::1:9200"`), which made `bind_address = "::1"` a node- // that could not start at all.- //- // `socket_addr` cannot be `None` here: step 3a rejected an- // unparseable `bind_address` before the data directory existed, which- // is where that failure belongs. The context is kept as a backstop so- // that if a future edit reorders or drops 3a, this still names the- // setting rather than surfacing a bare `Option` unwrap.- let rest_addr: SocketAddr = cfg- .socket_addr(cfg.server.rest_port)- .with_context(|| bad_bind_address(&cfg))?;- let es_addr: SocketAddr = cfg- .socket_addr(cfg.server.es_compat_port)- .with_context(|| bad_bind_address(&cfg))?;- let grpc_addr: SocketAddr = cfg- .socket_addr(cfg.server.grpc_port)- .with_context(|| bad_bind_address(&cfg))?;+ // 10/10a. Bind addresses + listeners: moved up to step 8c, ahead of the+ // console bootstrap at step 9, so the setup link it prints is+ // built from a port this process actually holds (issue #469).+ // `rest_addr`/`es_addr`/`grpc_addr`, the three listeners, and+ // `bound` all still live from there.- // 10a. Bind all three listeners NOW — before the banner, before anything- // reports readiness, and fatally.- //- // This used to happen inside the three `tokio::spawn`s below, where a- // bind error was `error!`-logged and explicitly non-fatal. Because- // `tokio::join!` returns only when all three tasks end, a node that- // lost just one port stayed up — and the banner, printed earlier,- // had already announced that port and this data directory as its own.- //- // That is not a cosmetic lie. The node that *does* own :9200 answers- // `GET /_cluster/health` with `green`, which is the readiness probe- // the docs prescribe, so `xerj autoindex` proceeds and streams the- // user's corpus into a datastore they have never heard of. It was- // reported by three independent agents; one of them put 905 files —- // contracts, invoices, a bank export — into another node's data- // directory and got `ok=true exit=0` for it (issue #465).- //- // Binding first collapses the whole class: the kernel decides who- // owns the port before we make any claim about owning it.- let rest_listener = bind_listener(rest_addr, "native REST")?;- let es_listener = bind_listener(es_addr, "ES-compat")?;- let grpc_listener = bind_listener(grpc_addr, "gRPC")?;-- // 11. Banner (includes total startup time). Printed from the addresses the- // kernel gave us, so every port on it is one this process holds.- let bound = BoundAddrs {- rest: rest_listener- .local_addr()- .context("native REST: read the bound address")?,- es: es_listener- .local_addr()- .context("ES-compat: read the bound address")?,- grpc: grpc_listener- .local_addr()- .context("gRPC: read the bound address")?,- };+ // 11. Banner (includes total startup time). Printed from `bound` (8c) —+ // the addresses the kernel gave us — so every port on it is one this+ // process holds.let startup_ms = startup_start.elapsed().as_millis();info!("startup complete in {}ms", startup_ms);print_banner(&cfg, &bound, startup_ms);diff --git a/engine/crates/xerj-server/tests/ephemeral_port_console_link.rs b/engine/crates/xerj-server/tests/ephemeral_port_console_link.rsnew file mode 100644index 000000000..1c8cf5898--- /dev/null+++ b/engine/crates/xerj-server/tests/ephemeral_port_console_link.rs@@ -0,0 +1,208 @@+//! Issue #469: the first-launch console setup link must name a port the node+//! actually holds, not the one it was asked for.+//!+//! The link used to be built from `cfg.server.es_compat_port` — the+//! *requested* port — and printed at the old step 9, before any listener was+//! bound (binding happened at the old step 10a). With an ephemeral port+//! (`es_compat_port = 0`) that produced a link like+//! `http://127.0.0.1:0/_xerj-console/setup#token=…`: `:0` is never a+//! reachable address, so the single action a first-run operator is told to+//! take could not be followed. #466 fixed the same class of problem for the+//! startup banner by binding every listener first and printing from+//! `local_addr()`; this is that same treatment applied to the console link.+//!+//! This is a process-level test, like `taken_port_fails_startup.rs`: the+//! defect is in how `main.rs` sequences the bind against the console+//! bootstrap, which is invisible from inside `xerj-console-api` (its own unit+//! tests pass a `bind_url` the caller already built correctly).++use std::io::Read;+use std::net::TcpListener;+use std::process::{Command, Stdio};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++fn toml_path(p: &std::path::Path) -> String {+ p.to_string_lossy().replace('\\', "/")+}++/// `rest_port`/`grpc_port` pinned to two free ports; `es_compat_port = 0` so+/// the kernel assigns the ES-compat listener whatever it has free — the+/// ephemeral-port case the issue reports against.+fn config_with_ephemeral_es_port(dir: &std::path::Path, rest: u16, grpc: u16) -> String {+ format!(+ r#"+[server]+bind_address = "127.0.0.1"+rest_port = {rest}+grpc_port = {grpc}+es_compat_port = 0+data_dir = "{data}"++[limits]+disk_flood_stage_percent = 0+"#,+ data = toml_path(&dir.join("data")),+ )+}++fn two_free_ports() -> (u16, u16) {+ let held: Vec<TcpListener> = (0..2)+ .map(|_| TcpListener::bind("127.0.0.1:0").unwrap())+ .collect();+ let p: Vec<u16> = held+ .iter()+ .map(|l| l.local_addr().unwrap().port())+ .collect();+ (p[0], p[1])+}++struct Outcome {+ stdout: String,+ stderr: String,+}++/// Read `r` a chunk at a time, appending everything into `buf`, until EOF —+/// meant to run on its own thread against a still-live child pipe, since a+/// blocking `read` only returns once the child writes or closes it.+fn drain_into(mut r: impl Read, buf: Arc<Mutex<String>>) {+ let mut chunk = [0u8; 4096];+ loop {+ match r.read(&mut chunk) {+ Ok(0) => break,+ Ok(n) => buf+ .lock()+ .unwrap()+ .push_str(&String::from_utf8_lossy(&chunk[..n])),+ Err(_) => break,+ }+ }+}++/// Spawn the real binary and poll its stdout/stderr for `until` to become+/// true, up to `timeout`, then kill it — this is a first-launch boot with no+/// active user yet, so it never exits on its own. Two reader threads drain+/// the pipes concurrently so a quiet stdout (still building system indices)+/// never blocks us from seeing what stderr already has, or vice versa.+fn boot_until(+ config_body: &str,+ dir: &std::path::Path,+ timeout: Duration,+ until: impl Fn(&str, &str) -> bool,+) -> Outcome {+ let config_path = dir.join("xerj.toml");+ std::fs::write(&config_path, config_body).unwrap();++ let mut child = Command::new(env!("CARGO_BIN_EXE_xerj"))+ .arg("--config")+ .arg(&config_path)+ .arg("--insecure")+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn xerj");++ let stdout_buf = Arc::new(Mutex::new(String::new()));+ let stderr_buf = Arc::new(Mutex::new(String::new()));+ let out_r = child.stdout.take().expect("stdout piped");+ let err_r = child.stderr.take().expect("stderr piped");+ let out_buf_t = stdout_buf.clone();+ let err_buf_t = stderr_buf.clone();+ let out_thread = std::thread::spawn(move || drain_into(out_r, out_buf_t));+ let err_thread = std::thread::spawn(move || drain_into(err_r, err_buf_t));++ let deadline = Instant::now() + timeout;+ loop {+ {+ let so = stdout_buf.lock().unwrap();+ let se = stderr_buf.lock().unwrap();+ if until(&so, &se) || Instant::now() > deadline {+ break;+ }+ }+ std::thread::sleep(Duration::from_millis(50));+ }++ child.kill().ok();+ child.wait().ok();+ out_thread.join().ok();+ err_thread.join().ok();++ Outcome {+ stdout: Arc::try_unwrap(stdout_buf).unwrap().into_inner().unwrap(),+ stderr: Arc::try_unwrap(stderr_buf).unwrap().into_inner().unwrap(),+ }+}++/// Pull the port out of `…http://host:PORT/_xerj-console/setup#token=…`.+fn port_from_setup_link(stderr: &str) -> Option<u16> {+ let marker = "/_xerj-console/setup#token=";+ let end = stderr.find(marker)?;+ let authority_end = &stderr[..end];+ let start = authority_end.rfind("http://")?;+ let authority = &authority_end[start + "http://".len()..end];+ let port_str = authority.rsplit(':').next()?;+ port_str.parse().ok()+}++/// Pull the port out of the banner's `ES-compat 127.0.0.1:PORT [...]` line.+fn port_from_banner(stdout: &str) -> Option<u16> {+ let line = stdout+ .lines()+ .find(|l| l.trim_start().starts_with("ES-compat"))?;+ let after_colon = line.rsplit_once(':')?.1;+ let digits: String = after_colon+ .chars()+ .take_while(|c| c.is_ascii_digit())+ .collect();+ digits.parse().ok()+}++/// The whole defect in one assertion: with `es_compat_port = 0`, the port+/// named in the first-launch setup link must be a real, non-zero port — and+/// specifically the one the banner (already fixed by #466, from+/// `local_addr()`) reports the node actually bound.+#[test]+fn ephemeral_es_port_console_link_names_the_bound_port() {+ let dir = tempfile::tempdir().unwrap();+ let (rest, grpc) = two_free_ports();++ let out = boot_until(+ &config_with_ephemeral_es_port(dir.path(), rest, grpc),+ dir.path(),+ Duration::from_secs(60),+ |stdout, stderr| {+ stdout.contains("ES-compat") && stderr.contains("/_xerj-console/setup#token=")+ },+ );++ let link_port = port_from_setup_link(&out.stderr).unwrap_or_else(|| {+ panic!(+ "no first-launch setup link found on stderr within the boot window\n\+ --- stdout ---\n{}\n--- stderr ---\n{}",+ out.stdout, out.stderr+ )+ });+ let banner_port = port_from_banner(&out.stdout).unwrap_or_else(|| {+ panic!(+ "no ES-compat banner line found on stdout within the boot window\n\+ --- stdout ---\n{}\n--- stderr ---\n{}",+ out.stdout, out.stderr+ )+ });++ assert_ne!(+ link_port, 0,+ "the setup link named port 0 — unreachable, and the exact bug \+ (issue #469): `es_compat_port = 0` leaked into the link instead of \+ the port the kernel actually bound\n--- stderr ---\n{}",+ out.stderr+ );+ assert_eq!(+ link_port, banner_port,+ "the setup link named a different port than the banner — the node \+ is telling the operator to open a URL it is not listening \+ on\n--- stdout ---\n{}\n--- stderr ---\n{}",+ out.stdout, out.stderr+ );+}