Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 18 additions & 3 deletions crates/trigger-http/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{
future::Future,
io::{ErrorKind, IsTerminal},
net::SocketAddr,
sync::Arc,
sync::{Arc, OnceLock},
time::Duration,
};

Expand Down Expand Up @@ -60,8 +60,14 @@ pub const MAX_RETRIES: u16 = 10;

/// An HTTP server which runs Spin apps.
pub struct HttpServer<F: RuntimeFactors> {
/// The address the server is listening on.
/// The address the server was configured to listen on (the `--listen` value).
listen_addr: SocketAddr,
/// The address the server is actually bound to, captured once after binding.
///
/// This can differ from `listen_addr` when the OS assigns the port — e.g.
/// `--listen 127.0.0.1:0` or `--find-free-port`. Self-request origins must use
/// this real address rather than the configured one.
local_addr: OnceLock<SocketAddr>,
/// The TLS configuration for the server.
tls_config: Option<TlsConfig>,
/// The maximum buffer size for an HTTP1 connection.
Expand Down Expand Up @@ -151,6 +157,7 @@ impl<F: RuntimeFactors> HttpServer<F> {
.collect::<anyhow::Result<_>>()?;
Ok(Self {
listen_addr,
local_addr: OnceLock::new(),
tls_config,
find_free_port,
router,
Expand Down Expand Up @@ -207,6 +214,8 @@ impl<F: RuntimeFactors> HttpServer<F> {
})?
};

let _ = self.local_addr.set(listener.local_addr()?);

if let Some(tls_config) = self.tls_config.clone() {
self.serve_https(listener, tls_config).await?;
} else {
Expand Down Expand Up @@ -366,6 +375,10 @@ impl<F: RuntimeFactors> HttpServer<F> {
}
}

fn get_local_addr(&self) -> SocketAddr {
self.local_addr.get().copied().unwrap_or(self.listen_addr)
}

async fn respond_wasm_component(
self: &Arc<Self>,
req: Request<Body>,
Expand All @@ -386,7 +399,9 @@ impl<F: RuntimeFactors> HttpServer<F> {
.context(
"The wasi HTTP trigger was configured without the required wasi outbound http support",
)?;
let origin = SelfRequestOrigin::create(server_scheme, &self.listen_addr.to_string())?;

let self_addr = self.get_local_addr();
let origin = SelfRequestOrigin::create(server_scheme, &self_addr.to_string())?;
outbound_http.set_self_request_origin(origin);
outbound_http.set_request_interceptor(OutboundHttpInterceptor::new(self.clone()))?;

Expand Down
2 changes: 2 additions & 0 deletions tests/testing-framework/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ http-body-util = { workspace = true }
log = "0.4"
nix = "0.29"
reqwest = { workspace = true }
serde_json = { workspace = true }
test-environment = { workspace = true }
spin-app = { path = "../../crates/app" }
spin-http = { path = "../../crates/http" }
Expand All @@ -18,3 +19,4 @@ spin-runtime-factors = { path = "../../crates/runtime-factors" }
spin-trigger = { path = "../../crates/trigger" }
spin-trigger-http = { path = "../../crates/trigger-http" }
tokio = { workspace = true }
url = { workspace = true }
64 changes: 45 additions & 19 deletions tests/testing-framework/src/runtimes/spin_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,15 @@ impl SpinCli {
spin_config: SpinConfig,
env: &mut TestEnvironment<R>,
) -> anyhow::Result<Self> {
let port = get_random_port()?;
let mut spin_cmd = Command::new(spin_config.binary_path);
let child = spin_cmd
.envs(env.env_vars())
.arg("up")
.current_dir(env.path())
.args(["--listen", &format!("127.0.0.1:{port}")])
// Bind an OS-assigned free port on Spin's own listener and read the actual
// port back from its startup output. Pre-allocating a port here is racy
// because parallel tests can claim it before `spin up` binds.
.args(["--listen", "127.0.0.1:0"])
.args(spin_config.spin_up_args)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
Expand All @@ -72,24 +74,31 @@ impl SpinCli {
let mut child = child.spawn()?;
let stdout = OutputStream::new(child.stdout.take().unwrap());
let stderr = OutputStream::new(child.stderr.take().unwrap());
log::debug!("Awaiting spin binary to start up on port {port}...");
log::debug!("Awaiting spin binary to report its listening port...");
let mut spin = Self {
process: child,
stdout,
stderr,
io_mode: IoMode::Http(port),
io_mode: IoMode::None,
};
let start = std::time::Instant::now();
loop {
match std::net::TcpStream::connect(format!("127.0.0.1:{port}")) {
Ok(_) => {
log::debug!("Spin started on port {port}.");
return Ok(spin);
}
Err(e) => {
let stderr = spin.stderr.output_as_str().unwrap_or("<non-utf8>");
log::trace!("Checking that the Spin server started returned an error: {e}");
log::trace!("Current spin stderr = '{stderr}'");
// `spin up` prints its base URL once the listener is bound and the app is
// loaded. Observing it confirms readiness and tells us the real port the OS
// assigned to this Spin instance.
let found_port = spin.stdout.output_as_str().and_then(parse_serving_port);
if let Some(port) = found_port {
match std::net::TcpStream::connect(("127.0.0.1", port)) {
Ok(_) => {
log::debug!("Spin started on port {port}.");
spin.io_mode = IoMode::Http(port);
return Ok(spin);
}
Err(e) => {
log::trace!(
"Spin reported port {port}, but it is not accepting connections yet: {e}"
);
}
}
}
if let Some(status) = spin.try_wait()? {
Expand All @@ -107,7 +116,8 @@ impl SpinCli {
std::thread::sleep(std::time::Duration::from_millis(50));
}
anyhow::bail!(
"`spin up` did not start server or error after two minutes. stderr:\n\t{}",
"`spin up` did not report a listening port within two minutes.\nstdout:\n\t{}\nstderr:\n\t{}",
spin.stdout.output_as_str().unwrap_or("<non-utf8>"),
spin.stderr.output_as_str().unwrap_or("<non-utf8>")
)
}
Expand Down Expand Up @@ -278,9 +288,25 @@ enum IoMode {
None,
}

/// Uses a track to ge a random unused port
fn get_random_port() -> anyhow::Result<u16> {
Ok(std::net::TcpListener::bind("localhost:0")?
.local_addr()?
.port())
fn parse_serving_port(output: &str) -> Option<u16> {
parse_plain_serving_port(output).or_else(|| parse_json_serving_port(output))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wait, don't we know whether it's printing JSON or plain text?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There was a test I added in the previous PR for testing JSON output, and all other tests are plain text. I can update the test code to force every test to output JSON, which is easier to handle. How does that sound?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking more that we would be able to know when calling parse_serving_port whether the output was set to JSON. But maybe that info is buried in some Command arg that appears only in a callback somewhere and is inaccessible. It's fine to leave this as is.

}

fn parse_plain_serving_port(output: &str) -> Option<u16> {
output
.lines()
.filter_map(|line| line.trim().strip_prefix("Serving "))
.find_map(parse_base_url_port)
}

fn parse_json_serving_port(output: &str) -> Option<u16> {
let output: serde_json::Value = serde_json::from_str(output).ok()?;
output
.get("base_url")
.and_then(serde_json::Value::as_str)
.and_then(parse_base_url_port)
}

fn parse_base_url_port(base_url: &str) -> Option<u16> {
url::Url::parse(base_url).ok()?.port_or_known_default()
}
Loading