use std::time::Duration;
use wasmtime_wasi_http::p2::body::HyperOutgoingBody;
use wasmtime_wasi_http::p2::types::OutgoingRequestConfig;
use wasmtime_wasi_http::p2::{HttpResult, WasiHttpHooks, default_send_request, types};
pub(crate) const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) const HTTP_TIMEOUT_ENV: &str = "GREENTIC_HTTP_OUTBOUND_TIMEOUT_SECS";
pub(crate) fn ceiling_from(raw: Option<&str>) -> Duration {
raw.and_then(|v| v.trim().parse::<u64>().ok())
.filter(|secs| *secs > 0)
.map(Duration::from_secs)
.unwrap_or(DEFAULT_HTTP_TIMEOUT)
}
pub(crate) fn ceiling() -> Duration {
ceiling_from(std::env::var(HTTP_TIMEOUT_ENV).ok().as_deref())
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct HttpTimeoutHooks {
ceiling: Duration,
}
impl HttpTimeoutHooks {
pub(crate) fn from_env() -> Self {
Self { ceiling: ceiling() }
}
#[cfg(test)]
fn with_ceiling(ceiling: Duration) -> Self {
Self { ceiling }
}
}
fn clamp_config(config: OutgoingRequestConfig, ceiling: Duration) -> OutgoingRequestConfig {
OutgoingRequestConfig {
use_tls: config.use_tls,
connect_timeout: config.connect_timeout.min(ceiling),
first_byte_timeout: config.first_byte_timeout.min(ceiling),
between_bytes_timeout: config.between_bytes_timeout.min(ceiling),
}
}
impl WasiHttpHooks for HttpTimeoutHooks {
fn send_request(
&mut self,
request: hyper::Request<HyperOutgoingBody>,
config: OutgoingRequestConfig,
) -> HttpResult<types::HostFutureIncomingResponse> {
let clamped = clamp_config(config, self.ceiling);
Ok(default_send_request(request, clamped))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ceiling_from_missing_env_falls_back_to_default() {
assert_eq!(ceiling_from(None), DEFAULT_HTTP_TIMEOUT);
}
#[test]
fn ceiling_from_unparseable_env_falls_back_to_default() {
assert_eq!(ceiling_from(Some("not-a-number")), DEFAULT_HTTP_TIMEOUT);
}
#[test]
fn ceiling_from_zero_falls_back_to_default() {
assert_eq!(ceiling_from(Some("0")), DEFAULT_HTTP_TIMEOUT);
}
#[test]
fn ceiling_from_valid_env_is_honored() {
assert_eq!(ceiling_from(Some("45")), Duration::from_secs(45));
}
#[test]
fn ceiling_from_env_trims_whitespace() {
assert_eq!(ceiling_from(Some(" 45 ")), Duration::from_secs(45));
}
#[test]
fn clamp_config_lowers_a_longer_or_absent_field() {
let ceiling = Duration::from_secs(10);
let config = OutgoingRequestConfig {
use_tls: false,
connect_timeout: Duration::from_secs(600),
first_byte_timeout: Duration::from_secs(600),
between_bytes_timeout: Duration::from_secs(600),
};
let clamped = clamp_config(config, ceiling);
assert_eq!(clamped.connect_timeout, Duration::from_secs(10));
assert_eq!(clamped.first_byte_timeout, Duration::from_secs(10));
assert_eq!(clamped.between_bytes_timeout, Duration::from_secs(10));
}
#[test]
fn a_guest_supplied_shorter_value_is_never_raised() {
let ceiling = Duration::from_secs(30);
let guest_value = Duration::from_secs(3);
let config = OutgoingRequestConfig {
use_tls: false,
connect_timeout: guest_value,
first_byte_timeout: guest_value,
between_bytes_timeout: guest_value,
};
let clamped = clamp_config(config, ceiling);
assert_eq!(
clamped.connect_timeout, guest_value,
"a 3s guest value must survive unchanged against a 30s ceiling"
);
assert_eq!(clamped.first_byte_timeout, guest_value);
assert_eq!(clamped.between_bytes_timeout, guest_value);
}
#[test]
fn a_guest_supplied_longer_value_is_lowered() {
let ceiling = Duration::from_secs(30);
let guest_value = Duration::from_secs(600);
let config = OutgoingRequestConfig {
use_tls: false,
connect_timeout: guest_value,
first_byte_timeout: guest_value,
between_bytes_timeout: guest_value,
};
let clamped = clamp_config(config, ceiling);
assert_eq!(
clamped.connect_timeout, ceiling,
"a 600s guest value must be lowered to the 30s ceiling"
);
assert_eq!(clamped.first_byte_timeout, ceiling);
assert_eq!(clamped.between_bytes_timeout, ceiling);
}
fn test_request(addr: std::net::SocketAddr) -> hyper::Request<HyperOutgoingBody> {
use http_body_util::BodyExt;
hyper::Request::builder()
.uri(format!("http://{addr}"))
.body(
http_body_util::Empty::<bytes::Bytes>::new()
.map_err(|_: std::convert::Infallible| unreachable!())
.boxed_unsync(),
)
.unwrap()
}
#[tokio::test]
async fn send_request_bounds_wall_time_to_the_ceiling() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("failed to bind an ephemeral localhost port");
let addr = listener
.local_addr()
.expect("failed to read the bound local address");
tokio::spawn(async move {
if let Ok((_stream, _peer)) = listener.accept().await {
std::future::pending::<()>().await;
}
});
let ceiling = Duration::from_millis(300);
let mut hooks = HttpTimeoutHooks::with_ceiling(ceiling);
let config = OutgoingRequestConfig {
use_tls: false,
connect_timeout: Duration::from_secs(600),
first_byte_timeout: Duration::from_secs(600),
between_bytes_timeout: Duration::from_secs(600),
};
let request = test_request(addr);
let start = std::time::Instant::now();
let response = hooks
.send_request(request, config)
.expect("send_request should not fail synchronously");
let types::HostFutureIncomingResponse::Pending(handle) = response else {
panic!("expected Pending — default_send_request always spawns");
};
let outer = handle.await;
let elapsed = start.elapsed();
assert!(
elapsed < Duration::from_secs(5),
"expected the 300ms ceiling to bound wall time, took {elapsed:?}"
);
let inner = outer.expect(
"expected a host-level Ok wrapping the guest-visible result, got a host-level Err",
);
assert!(
inner.is_err(),
"expected a first-byte-timeout failure, got a real response: {inner:?}"
);
}
}