iroh-relay: wire spawn() into fn main with graceful shutdown

- IrohRelayHandle::shutdown() consumes self and awaits Server::shutdown()
  (which drains in-flight QUIC sessions before returning), replacing the
  previous drop-aborts-supervisor pattern.

- main.rs::serve() now starts the embedded iroh-relay when *both*
  SPROUT_IROH_RELAY_PUBLIC_URL and SPROUT_IROH_RELAY_BIND_ADDR are set.
  Spawned alongside the HTTP listener; subscribed to the same shutdown_tx
  watcher so SIGTERM/Ctrl-C drains the iroh-relay together with axum.

- Mismatched config logs a warn! and starts neither:
    * URL only  -> NIP-11 advertises a phantom endpoint -> mesh-LLM is broken
    * bind only -> clients can't build the NIP-98 'u' tag -> 100% denial
  In both cases we fail loud and refuse to lie to clients.

- Both serve() paths (UDS-enabled + TCP-only) await the iroh drain task
  before returning so shutdown is actually graceful end-to-end.

sprout-relay --lib: 208/208 unit tests pass (unchanged; this is a wiring
change, not an auth change).
workspace clippy -D warnings: clean.
workspace cargo fmt --check: clean.

Signed-off-by: Tyler Longwell <109685178+tlongwell-block@users.noreply.github.com>
Co-authored-by: Dawn (sprout agent) <c6237ef84fa537c78dcee78efd2d4e59f728859c7f194da42ac51ededfa0be05@sprout-oss.stage.blox.sqprod.co>
This commit is contained in:
tlongwell-block
2026-05-19 16:45:31 -04:00
parent 2d818b6efd
commit db6c1103aa
2 changed files with 88 additions and 3 deletions

View File

@@ -69,13 +69,30 @@ const NIP98_METHOD: &str = "GET";
/// able to coerce the relay into multi-megabyte allocations.
const MAX_BEARER_LEN: usize = 64 * 1024;
/// Handle returned by [`spawn`] — dropping it stops the server.
/// Handle returned by [`spawn`].
///
/// Dropping the handle aborts the iroh-relay supervisor task (via
/// `AbortOnDropHandle` inside `Server`). For graceful drain, prefer
/// [`IrohRelayHandle::shutdown`] which waits for in-flight connections to
/// finish before returning.
pub struct IrohRelayHandle {
/// The bound HTTP address (resolved if the caller passed port 0).
pub http_addr: Option<SocketAddr>,
/// The bound HTTPS address, if TLS was configured.
pub https_addr: Option<SocketAddr>,
_server: Server,
server: Server,
}
impl IrohRelayHandle {
/// Request graceful shutdown of the embedded iroh-relay.
///
/// Returns once all relay tasks have stopped. Used by the Sprout main
/// shutdown loop so SIGTERM stops admitting new mesh-LLM connections
/// alongside the HTTP listener, instead of yanking the socket out from
/// under in-flight QUIC sessions.
pub async fn shutdown(self) -> Result<(), iroh_relay::server::SupervisorError> {
self.server.shutdown().await
}
}
/// Spawn an embedded iroh-relay bound to `bind_addr`, gated by Sprout's
@@ -128,7 +145,7 @@ pub async fn spawn(
Ok(Some(IrohRelayHandle {
http_addr: server.http_addr(),
https_addr: server.https_addr(),
_server: server,
server,
}))
}

View File

@@ -11,6 +11,7 @@ use sprout_pubsub::PubSubManager;
use sprout_search::{SearchConfig, SearchService};
use sprout_relay::config::Config;
use sprout_relay::iroh_relay;
use sprout_relay::metrics as relay_metrics;
use sprout_relay::router::{build_health_router, build_router};
use sprout_relay::state::AppState;
@@ -482,6 +483,65 @@ async fn serve(
.map_err(|e| anyhow::anyhow!("Failed to bind {}: {e}", config.bind_addr))?;
info!(addr = %config.bind_addr, "sprout-relay TCP listening");
// ── Embedded iroh-relay (mesh-LLM, optional) ─────────────────────────────
// Started only when both `SPROUT_IROH_RELAY_PUBLIC_URL` and
// `SPROUT_IROH_RELAY_BIND_ADDR` are configured. Advertising a URL without
// a listener (or vice-versa) is a deploy footgun, so we log loudly and
// refuse to start the iroh-relay if exactly one is set.
let iroh_relay_task = match (
config.iroh_relay_public_url.as_deref(),
config.iroh_relay_bind_addr,
) {
(Some(_), Some(bind_addr)) => {
match iroh_relay::spawn(Arc::clone(&state), bind_addr).await {
Ok(Some(handle)) => {
info!(
bind_addr = %bind_addr,
http_addr = ?handle.http_addr,
"embedded iroh-relay started",
);
let mut iroh_rx = shutdown_tx.subscribe();
Some(tokio::spawn(async move {
// Wait for the workspace shutdown signal, then drain
// the iroh-relay gracefully so in-flight QUIC sessions
// get a chance to finish.
iroh_rx.changed().await.ok();
info!("draining embedded iroh-relay");
if let Err(e) = handle.shutdown().await {
tracing::error!("embedded iroh-relay shutdown error: {e}");
}
}))
}
Ok(None) => {
// `spawn` returned None — likely an unparseable
// `iroh_relay_public_url`. Already logged inside `spawn`.
None
}
Err(e) => {
return Err(anyhow::anyhow!(
"Failed to spawn embedded iroh-relay on {bind_addr}: {e}"
));
}
}
}
(Some(_), None) => {
tracing::warn!(
"SPROUT_IROH_RELAY_PUBLIC_URL set but SPROUT_IROH_RELAY_BIND_ADDR is not — \
NIP-11 will advertise a URL that nothing serves. Mesh-LLM will not work.",
);
None
}
(None, Some(_)) => {
tracing::warn!(
"SPROUT_IROH_RELAY_BIND_ADDR set but SPROUT_IROH_RELAY_PUBLIC_URL is not — \
iroh-relay refused to start because clients cannot construct the canonical \
NIP-98 `u` tag without a public URL.",
);
None
}
(None, None) => None,
};
// ── App listener (UDS, optional) ─────────────────────────────────────────
#[cfg(unix)]
if let Some(ref uds_path) = config.uds_path {
@@ -524,6 +584,10 @@ async fn serve(
.map_err(|e| anyhow::anyhow!("TCP server error: {e}"))?;
uds_handle.abort();
if let Some(task) = iroh_relay_task {
// Already triggered by shutdown_tx; just wait for the drain task.
let _ = task.await;
}
return Ok(());
}
@@ -544,6 +608,10 @@ async fn serve(
.await
.map_err(|e| anyhow::anyhow!("Server error: {e}"))?;
if let Some(task) = iroh_relay_task {
let _ = task.await;
}
Ok(())
}