Skip to content
Merged
35 changes: 30 additions & 5 deletions crates/minimal/src/cmd/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,21 +304,46 @@ pub async fn cmd_ls(global: &GlobalArgs, args: LsArgs) -> Result<(), anyhow::Err
// fault this severe — `--raw` most of all, since a script parsing bare ids
// is exactly what will go on using hostnames that no longer resolve — and
// stdout stays clean for the parser either way.
warn_if_hostname_routing_down(resp.hostname_routing_unavailable.as_deref());
warn_if_hostname_routing_down(resp.hostname_routing_unavailable.as_deref(), "min ls");
warn_if_mtls_proxy_down(resp.mtls_proxy_unavailable.as_deref());
format_ls(&mut std::io::stdout(), &args, &resp)?;
Ok(())
}

/// Tells the user that `<name>.local.min.internal` will not resolve, and why.
/// The warning `min ls` and `min session activate` print when the daemon
/// reports hostname routing down: the daemon's reason and remedy for the
/// failed bind or publish, plus what recovery looks like from here — the
/// daemon retries with backoff and clears the warning on its own once the
/// listener recovers (NET-020, NET-022). `command` names the command the
/// warning rides on: re-running it shows the warning while the listener is
/// still down and nothing once it has recovered, so the recovery sentence
/// tells the user to re-run the command they are already in, not some other
/// one. Pure, so tests can assert the wording without capturing stderr.
#[must_use]
pub fn hostname_routing_warning(reason: &str, command: &str) -> String {
format!(
"warning: session hostnames will not route: {reason}. The daemon retries \
with backoff and clears this warning on its own once the listener \
recovers; run `{command}` again to check."
)
}
Comment thread
norrietaylor marked this conversation as resolved.
Resolved

/// Tells the user that `<name>.local.min.internal` will not resolve, and why,
/// and what clears it.
///
/// The daemon keeps serving without its host-side proxy, so nothing else the
/// user sees is different: sessions activate, exec works, the list prints. The
/// only other trace is a `warn!` in the daemon log, which is not where someone
/// watching curl fail is looking (gominimal/inbox#560).
pub(crate) fn warn_if_hostname_routing_down(reason: Option<&str>) {
/// watching curl fail is looking (gominimal/inbox#560). The daemon's report
/// carries the reason and the remedy for the cause (a held port, a failed
/// publish); the recovery is the daemon's job now — it retries with backoff
/// and the warning goes away by itself, so the remedy says to check again
/// rather than to restart anything. `command` names the command this runs
/// from, so the recovery sentence fits it — `min ls` on the list, `min
/// session activate` at activation.
pub(crate) fn warn_if_hostname_routing_down(reason: Option<&str>, command: &str) {
if let Some(reason) = reason {
eprintln!("warning: session hostnames will not route: {reason}");
eprintln!("{}", hostname_routing_warning(reason, command));
}
}

Expand Down
5 changes: 4 additions & 1 deletion crates/minimal/src/cmd/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,10 @@ pub(crate) async fn activate_session(
// loadout, and the finalize that #1251 died at, and with the session left
// unfinalized for the daemon to reap when this connection drops.
ensure_version_reported(created.daemon_version.as_deref())?;
warn_if_hostname_routing_down(created.hostname_routing_unavailable.as_deref());
warn_if_hostname_routing_down(
created.hostname_routing_unavailable.as_deref(),
"min session activate",
);
warn_if_mtls_proxy_down(created.mtls_proxy_unavailable.as_deref());
let id = created.id;

Expand Down
179 changes: 179 additions & 0 deletions crates/minimal/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,185 @@ async fn session_policy_succeeds() {
.unwrap();
}

// --- hostname routing warning (NET-020/NET-021/NET-022) ---
//
// The startup retry lives in `minimald::server` behind the Linux gate with the
// `net` module it drives, so this section is Linux-only too: it holds a port,
// runs the real retry loop against it, and reads what `min ls` and
// `min session activate` print while the proxy is down and after it recovers.

/// Runs the compiled `min` with the harness daemon's `--minimal-dir`, an empty
/// `--config-dir` (the developer's own loadouts and policy stay out of the
/// run), and `--no-input`, plus `extra` as the command, and returns stderr.
#[cfg(target_os = "linux")]
async fn run_min_stderr(args: &GlobalArgs, extra: &[&str]) -> String {
let minimal_dir = args
.minimal_dir
.as_ref()
.expect("setup points at a tempdir");
let config_dir = tempfile::TempDir::new().unwrap();
let out = tokio::process::Command::new(env!("CARGO_BIN_EXE_min"))
.args(["--minimal-dir".as_ref(), minimal_dir.as_os_str()])
.args(["--config-dir".as_ref(), config_dir.path().as_os_str()])
.arg("--no-input")
.args(extra)
.output()
.await
.expect("the min binary should be invocable");
String::from_utf8_lossy(&out.stderr).into_owned()
}

/// Polls `ListSessions` until the daemon reports hostname routing down — the
/// startup retry's first failed bind has landed on its note — and returns the
/// reason.
#[cfg(target_os = "linux")]
async fn wait_for_routing_failure(args: &GlobalArgs) -> String {
use minimald_rpc::ListSessions;

let mut client = connect_daemon(args).await.unwrap();
for _ in 0..200 {
let resp = client.oneshot_rpc::<ListSessions>(()).await.unwrap();
if let Some(reason) = resp.hostname_routing_unavailable {
return reason;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
panic!("the daemon never reported hostname routing down");
}

/// Holds a fresh port and starts the daemon's hostname-proxy startup retry
/// against it — the real loop `start_host_proxies` spawns, with a compressed
/// backoff — so the note `min ls` warns from is set exactly the way an
/// occupied proxy port sets it, without holding the production `:7654`.
/// Dropping the held listener frees the port; the returned task resolves once
/// the proxy is serving again and the note is cleared.
#[cfg(target_os = "linux")]
async fn hold_proxy_port_and_start_retry(
state: &minimald::server::ServerStateHandle,
) -> (tokio::net::TcpListener, tokio::task::JoinHandle<()>) {
use minimald::server::{RetryBackoff, retry_hostname_proxy_until_serving};

let held = tokio::net::TcpListener::bind(("127.0.0.1", 0))
.await
.unwrap();
let addr = held.local_addr().unwrap();
let retry = tokio::spawn(retry_hostname_proxy_until_serving(
state.clone(),
addr,
RetryBackoff::new(
std::time::Duration::from_millis(5),
std::time::Duration::from_millis(40),
),
));
(held, retry)
}

/// NET-020: with the proxy port occupied, both `min ls` and `min session
/// activate` print the failure's reason and the remedy for it, and say the
/// daemon recovers on its own. Driven through the compiled binary so the
/// assertion is on what the user actually sees.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn listener_failure_reported_with_remedy() {
let (daemon, args) = setup().await;
let (held, retry) = hold_proxy_port_and_start_retry(&daemon.server.state).await;
let reason = wait_for_routing_failure(&args).await;

let ls_stderr = run_min_stderr(&args, &["ls"]).await;
assert!(
ls_stderr.contains("warning: session hostnames will not route"),
"ls must warn about hostname routing, got: {ls_stderr}"
);
assert!(
ls_stderr.contains(&reason),
"ls must print the daemon's reason, got: {ls_stderr}"
);
assert!(
ls_stderr.contains("Remedy"),
"ls must print the remedy, got: {ls_stderr}"
);
assert!(
ls_stderr.contains("retries"),
"ls must say the daemon recovers on its own, got: {ls_stderr}"
);
assert!(
ls_stderr.contains("run `min ls` again to check"),
"ls must name the command its warning rides on, got: {ls_stderr}"
);

// `min session activate` prints the same report on its path.
let project = tempfile::TempDir::new().unwrap();
std::fs::create_dir(project.path().join(".git")).unwrap();
std::fs::write(
project.path().join("minimal.toml"),
"# test minimal.toml\n[upstream]\nrepo = \"https://github.com/gominimal/pkgs\"\nbranch = \"main\"\n\n[stack]\nuse = \"shell\"\n",
)
.unwrap();
let activate_stderr = run_min_stderr(
&args,
&[
"session",
"activate",
project.path().to_str().unwrap(),
"--name",
"remedy-report",
"--sync",
"tarball",
"--no-prompt",
],
)
.await;
assert!(
activate_stderr.contains("warning: session hostnames will not route"),
"activate must warn about hostname routing, got: {activate_stderr}"
);
assert!(
activate_stderr.contains(&reason),
"activate must print the daemon's reason, got: {activate_stderr}"
);
assert!(
activate_stderr.contains("Remedy"),
"activate must print the remedy, got: {activate_stderr}"
);
assert!(
activate_stderr.contains("run `min session activate` again to check"),
"activate must name the command its warning rides on, got: {activate_stderr}"
);

drop(held);
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), retry).await;
}

/// NET-022: once the port frees and the listener recovers, `min ls` stops
/// carrying the warning — against the same daemon process, with no restart.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn ls_warning_clears_on_recovery() {
let (daemon, args) = setup().await;
let (held, retry) = hold_proxy_port_and_start_retry(&daemon.server.state).await;
let _reason = wait_for_routing_failure(&args).await;

let before = run_min_stderr(&args, &["ls"]).await;
assert!(
before.contains("warning: session hostnames will not route"),
"ls must warn while the port is held, got: {before}"
);

// Free the port: the startup retry binds (a native daemon has no
// host-loopback publish gate) and clears the note.
drop(held);
tokio::time::timeout(std::time::Duration::from_secs(5), retry)
.await
.expect("the startup retry must finish once the port frees")
.expect("the startup retry must not panic");

let after = run_min_stderr(&args, &["ls"]).await;
assert!(
!after.contains("warning: session hostnames will not route"),
"the warning must clear without a daemon restart, got: {after}"
);
}

// --- helpers ---

/// Creates a session whose workspace mfile declares a `[session.vars]`
Expand Down
77 changes: 53 additions & 24 deletions crates/minimald/src/net/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,38 @@ fn split_authority(authority: &str) -> (&str, Option<u16>) {
(host, port)
}

/// Binds the egress-proxy listener at `addr`, returning it on success. On a bind
/// failure it emits the `component = "dns-proxy"` reachability warning and
/// returns `None`: the proxy is unavailable and PTask hostnames will not route
/// until the address is free. This is the daemon-startup reachability check that
/// supersedes the former systemd-resolved probe (R3.4).
/// Why a host-side proxy listener could not bind its address, carrying the
/// reason and the one remedy that clears it.
///
/// The pair is authored once here so every surface reads the same text: the
/// startup retry's warning, the daemon's `proxy_unavailable` note the
/// `ListSessions` RPC serves, and the warning `min ls` and
/// `min session activate` print (NET-020).
#[derive(Debug, Clone)]
pub struct BindFailure {
/// What failed, named for a human: the address and the OS error.
pub reason: String,
/// The remedy: free the listen address so the daemon's retry can bind it.
pub remedy: String,
}

impl BindFailure {
/// The reason and remedy as the one report the daemon's unavailable note
/// and the CLI warning carry.
#[must_use]
pub fn reported(&self) -> String {
format!("{}. Remedy: {}", self.reason, self.remedy)
}
}

/// Binds the egress-proxy listener at `addr`, returning it on success. On a
/// bind failure it returns a [`BindFailure`] carrying the reason (the address
/// and the OS error) and the remedy that clears it, and logs nothing: the
/// caller owns the failure's log line, because only it knows the retry
/// schedule that line reports — `server::start_host_proxies` retries with
/// backoff until the bind succeeds (NET-021), so one failed bind is one
/// warning, not a silent fallback. This is the daemon-startup reachability
/// check that supersedes the former systemd-resolved probe (R3.4).
///
/// The returned listener is the caller's to either serve (via [`serve`]) or
/// drop. The success event reports the address as `reachable` rather than
Expand All @@ -171,7 +198,12 @@ fn split_authority(authority: &str) -> (&str, Option<u16>) {
/// serve it (see `server::start_host_proxies`); this said otherwise, and reading
/// it as a bind-and-drop probe is what made gominimal/inbox#560 look like a
/// false alarm on macOS.
pub async fn bind_listener(addr: SocketAddr) -> Option<TcpListener> {
///
/// # Errors
///
/// Returns a [`BindFailure`] when the address cannot be bound; the OS error is
/// carried inside the failure's reason.
pub async fn bind_listener(addr: SocketAddr) -> Result<TcpListener, BindFailure> {
match TcpListener::bind(addr).await {
Ok(listener) => {
tracing::info!(
Expand All @@ -180,19 +212,15 @@ pub async fn bind_listener(addr: SocketAddr) -> Option<TcpListener> {
status = "reachable",
"host-side egress proxy listen address is bindable"
);
Some(listener)
}
Err(error) => {
tracing::warn!(
component = "dns-proxy",
%addr,
status = "unavailable",
error = %error,
remedy = "free the listen address; PTask *.min.internal hostnames will not route until the egress proxy can bind",
"host-side egress proxy could not bind its listener"
);
None
Ok(listener)
}
Err(error) => Err(BindFailure {
reason: format!("the daemon could not bind {addr}: {error}"),
remedy: format!(
"free the listen address; `lsof -nP -iTCP:{} -sTCP:LISTEN` names the holder",
addr.port()
),
}),
}
}

Expand Down Expand Up @@ -1058,15 +1086,16 @@ mod tests {
let listener = bind_listener(addr).await;
drop(guard);

assert!(listener.is_none(), "a bind to a held address must fail");
let logged = buf.contents();
let failure = listener.expect_err("a bind to a held address must fail");
assert!(
logged.contains(r#"component="dns-proxy""#),
"expected the dns-proxy component field, got: {logged}"
failure.reported().contains("could not bind"),
"the failure must name the bind failure, got: {}",
failure.reported()
);
let logged = buf.contents();
assert!(
logged.contains(r#"status="unavailable""#),
"expected the unavailable status field, got: {logged}"
logged.is_empty(),
"bind_listener must not log on failure; the caller owns the log line, got: {logged}"
);
}

Expand Down
Loading
Loading