diff --git a/CHANGELOG.md b/CHANGELOG.md index c438e6111..c7e6502f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -156,9 +156,15 @@ settings, and request records. eligible after the response attempt ends; its budget starts then, and the adapter cancels it before its next poll once the budget expires. A request may register at most 64 tasks, each with a budget of at most 30 s (`MAX_AFTER_RESPONSE_TASKS`, `MAX_AFTER_RESPONSE_BUDGET`). Adapters - without support return `501 Not Implemented` at registration. + without support return `501 Not Implemented` when no handle is installed or after an installed + handle's budget and task-limit checks pass. - Add the `after-response-tasks` capability: Axum and Fastly `BoundedCooperative`, - Cloudflare `BoundedCooperative` (#478), and Spin `Unsupported` (tracked in #483). + Cloudflare `BoundedCooperative` (#478), and Spin `Unsupported`. +- Spin installs a rejecting after-response scheduler on every converted request. Registrations + that pass core's budget and task-limit checks receive a `501` naming the adapter + (`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`), instead of core's generic message (#483). + A zero or over-limit budget on Spin now returns `500` before reaching the scheduler, instead + of the generic `501` returned when no handle was installed. - Axum production shutdown (`run_production_app*`, `run_app_with_options*`, `run_app_with_native_stores`) now waits for registered after-response tasks within the existing shutdown grace, after connections drain. Tasks still pending at the grace make shutdown fail with diff --git a/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs index 96aca4a2e..0a04442ee 100644 --- a/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs +++ b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs @@ -1,4 +1,9 @@ -//! Test-only source-bound proxy and verified TLS ingress. No response is collected here. +//! Test-only loopback proxy and verified TLS ingress. No response is collected here. +//! +//! Every proxy socket is on 127.0.0.1, the IPv4 loopback address every platform has, so the +//! server's direct peer is always a real 127.0.0.1 socket. An appending proxy writes the +//! predecessor it is given rather than its own socket peer: the server only sees that hop as +//! header text, and a real 127.0.0.1 predecessor would collide with the trusted peer. #![expect( clippy::arbitrary_source_item_ordering, reason = "fixture ownership precedes bounded relay helpers" @@ -27,18 +32,31 @@ use super::tests::reserve_or_spawn; const MAX_HEAD: usize = 0x8000; const RELAY_BUFFER: usize = 0x4000; +#[derive(Clone, Copy)] +pub(crate) struct Hop { + predecessor: IpAddr, + host: &'static str, + scheme: &'static str, +} + +impl Hop { + #[must_use] + #[inline] + pub(crate) const fn new(predecessor: IpAddr, host: &'static str, scheme: &'static str) -> Self { + Self { + predecessor, + host, + scheme, + } + } +} + #[derive(Clone, Copy)] pub(crate) enum Assertions { /// Keep deliberate malformed/gap inputs unchanged while preserving a real owned peer. Preserve, - AppendForwarded { - host: &'static str, - scheme: &'static str, - }, - AppendXForwarded { - host: &'static str, - scheme: &'static str, - }, + AppendForwarded(Hop), + AppendXForwarded(Hop), ReplaceForwarded { client: IpAddr, host: &'static str, @@ -61,12 +79,7 @@ impl LocalProxy { #[must_use] #[inline] - pub(crate) fn start( - upstream: SocketAddr, - source: Ipv4Addr, - assertions: Assertions, - tls: bool, - ) -> Self { + pub(crate) fn start(upstream: SocketAddr, assertions: Assertions, tls: bool) -> Self { let std_listener = { let _reserving = reserve_or_spawn(); StdTcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("proxy listener") @@ -93,13 +106,13 @@ impl LocalProxy { finished.map_err(io::Error::other)??; }, accepted = listener.accept(), if tasks.len() < 64 => { - let (socket, peer) = accepted?; + let (socket, _peer) = accepted?; let task_acceptor = tls_acceptor.clone(); tasks.spawn(async move { let operation = async { if let Some(acceptor) = task_acceptor { match acceptor.accept(socket).await { - Ok(mut client) => relay(&mut client, peer, upstream, source, assertions).await, + Ok(mut client) => relay(&mut client, upstream, assertions).await, // The wrong-name client sends this alert before any HTTP request. // Its test checks the exact certificate verification error separately. Err(error) if rejected_certificate(&error) => Ok(()), @@ -107,7 +120,7 @@ impl LocalProxy { } } else { let mut client = socket; - relay(&mut client, peer, upstream, source, assertions).await + relay(&mut client, upstream, assertions).await } }; timeout(Duration::from_secs(5), operation) @@ -203,7 +216,14 @@ where } } -fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result { +fn forwarded_node(address: IpAddr) -> String { + match address { + IpAddr::V4(ip) => ip.to_string(), + IpAddr::V6(ip) => format!("\"[{ip}]\""), + } +} + +fn rewrite(head: &str, assertions: Assertions) -> io::Result { let mut lines = head.split("\r\n"); let request = lines .next() @@ -214,13 +234,13 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result ip.to_string(), - IpAddr::V6(ip) => format!("\"[{ip}]\""), - }; match assertions { Assertions::Preserve => {} - Assertions::AppendForwarded { host, scheme } => { + Assertions::AppendForwarded(Hop { + predecessor, + host, + scheme, + }) => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("forwarded")) @@ -228,7 +248,8 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result>() .join(","); headers.retain(|(name, _)| !name.eq_ignore_ascii_case("forwarded")); - let assertion = format!("for={predecessor};host=\"{host}\";proto={scheme}"); + let node = forwarded_node(predecessor); + let assertion = format!("for={node};host=\"{host}\";proto={scheme}"); headers.push(( "Forwarded".into(), if previous.is_empty() { @@ -238,7 +259,11 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result { + Assertions::AppendXForwarded(Hop { + predecessor, + host, + scheme, + }) => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("x-forwarded-for")) @@ -246,7 +271,7 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result>() .join(","); headers.retain(|(name, _)| !name.to_ascii_lowercase().starts_with("x-forwarded-")); - let node = peer.ip().to_string(); + let node = predecessor.to_string(); headers.push(( "X-Forwarded-For".into(), if previous.is_empty() { @@ -269,10 +294,7 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result ip.to_string(), - IpAddr::V6(ip) => format!("\"[{ip}]\""), - }; + let node = forwarded_node(client); headers.push(( "Forwarded".into(), format!("for={node};host=\"{host}\";proto={scheme}"), @@ -293,20 +315,18 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result( client: &mut Client, - peer: SocketAddr, upstream: SocketAddr, - source: Ipv4Addr, assertions: Assertions, ) -> io::Result<()> where Client: AsyncRead + AsyncWrite + Unpin, { let (head, body_prefix) = read_head(client).await?; - let rewritten = rewrite(&head, peer, assertions)?; + let rewritten = rewrite(&head, assertions)?; let socket = { let _reserving = reserve_or_spawn(); let socket = TcpSocket::new_v4()?; - socket.bind(SocketAddr::new(IpAddr::V4(source), 0))?; + socket.bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0))?; socket }; let mut origin = socket.connect(upstream).await?; diff --git a/crates/edgezero-adapter-axum/tests/native_aws_startup.rs b/crates/edgezero-adapter-axum/tests/native_aws_startup.rs index 8dd6478e1..a48713e86 100644 --- a/crates/edgezero-adapter-axum/tests/native_aws_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_aws_startup.rs @@ -4,17 +4,13 @@ //! They exercise the public runner and real pinned SDK, not a provider seam. No AWS account, //! DNS hostname, external socket, image, or real cloud credential is used. -#[cfg(test)] -#[path = "fixtures/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] #[expect( clippy::arbitrary_source_item_ordering, reason = "loopback fixture helpers remain grouped before startup scenarios" )] mod tests { - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::fmt::Write as _; use std::fs; use std::io::{self, ErrorKind, Read, Write as _}; diff --git a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs index 93174c07c..96cfd2849 100644 --- a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs @@ -10,6 +10,7 @@ #[cfg(test)] mod tests { + use edgezero_core::test_net::accept_blocking; use std::fs; use std::io::{ErrorKind, Read, Write as _}; use std::net::{SocketAddr, TcpListener, TcpStream}; @@ -72,7 +73,7 @@ mod tests { let worker_stop = Arc::clone(&stop); thread::spawn(move || { while !worker_stop.load(Ordering::Relaxed) { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback()); stream diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index 3ec8d4acf..dc6a11b51 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -15,7 +15,7 @@ mod native_proxy; reason = "subprocess fixtures group setup, process ownership and acceptance scenarios" )] mod tests { - use super::native_proxy::{Assertions, LocalProxy, verified_tls_request}; + use super::native_proxy::{Assertions, Hop, LocalProxy, verified_tls_request}; use std::collections::HashSet; use std::ffi::{OsStr, OsString}; use std::fs; @@ -36,11 +36,13 @@ mod tests { const WAIT: Duration = Duration::from_secs(5); const STARTUP_PROBE_TIMEOUT: Duration = Duration::from_millis(50); const BIND_IN_USE: &str = "startup bind: listener: address in use"; - const PROXY_SOURCE: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 2); - const INGRESS_SOURCE: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 3); /// Launch attempts before a host that keeps losing its released port fails the test. const SPAWN_ATTEMPTS: usize = 3; + /// The visitor address an appending test proxy reports as its predecessor. It lies outside + /// every trusted range, so a chain walk that accepts it stopped at the proxy's assertion. + const VISITOR: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)); + struct Roots { config: TempDir, cwd: TempDir, @@ -106,7 +108,7 @@ mod tests { let _reserving = reserve_or_spawn(); let socket = TcpSocket::new_v4().expect("port reservation socket"); socket - .bind(SocketAddr::from(([127, 0, 0, 1], 0))) + .bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))) .expect("port reservation"); let addr = socket.local_addr().expect("reserved address"); (addr, socket) @@ -582,13 +584,18 @@ mod tests { assert!(id.bytes().all(|byte| byte.is_ascii_hexdigit())); } - fn assert_peer_ip(value: &Value, expected: Ipv4Addr) { + fn assert_peer_ip(value: &Value, expected: Ipv4Addr, listener: SocketAddr) { let peer: SocketAddr = value["handler"]["peer"] .as_str() .expect("owned peer") .parse() .expect("socket peer"); assert_eq!(peer.ip(), IpAddr::V4(expected)); + assert_ne!( + peer.port(), + listener.port(), + "accepted peer must not be the listener" + ); } fn assert_no_diagnostic_headers(response: &str) { @@ -621,31 +628,6 @@ mod tests { launch } - fn require_proxy_sources(test: &str, sources: &[Ipv4Addr]) -> bool { - let mut available = true; - for &source in sources { - let _reserving = reserve_or_spawn(); - let socket = TcpSocket::new_v4().expect("proxy source probe socket"); - match socket.bind(SocketAddr::from((source, 0))) { - Ok(()) => {} - Err(error) - if cfg!(target_os = "macos") - && error.kind() == io::ErrorKind::AddrNotAvailable => - { - // Write directly to stderr so libtest does not capture a passing skip. - writeln!( - io::stderr().lock(), - "skipping {test}: cannot bind {source}; run `sudo ifconfig lo0 alias {source} up` and rerun" - ) - .expect("proxy skip notice"); - available = false; - } - Err(error) => panic!("{test} requires binding {source}: {error}"), - } - } - available - } - fn assert_final_zero(server: &Server) { let snapshots = captured_json(&server.log(), "FINAL_SNAPSHOT "); assert_eq!( @@ -739,7 +721,7 @@ mod tests { for field in ["client_source", "host_source", "scheme_source"] { assert_eq!(value["handler"][field], "direct"); } - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); let expected_bytes = request .split("\r\n") .skip(1) @@ -767,15 +749,14 @@ mod tests { } #[test] - fn native_source_bound_single_proxy_and_mapped_cidr_match_only_owned_peers() { - if !require_proxy_sources("native single-proxy test", &[PROXY_SOURCE]) { - return; - } + fn native_single_loopback_proxy_requires_matching_peer_cidr() { + // The mapped /127 truncates to 127.0.0.0/31, so 127.0.0.0/32 is the sibling of the + // peer inside that range and the one listed network that does not own it. for networks in [ - "127.0.0.2/32", - "::ffff:127.0.0.2/128", - "::ffff:127.0.0.2/127", - "127.0.0.3/32", + "127.0.0.1/32", + "::ffff:127.0.0.1/128", + "::ffff:127.0.0.1/127", + "127.0.0.0/32", ] { let roots = Roots::new(); let addr = address(); @@ -786,11 +767,7 @@ mod tests { server.ready(); let proxy = LocalProxy::start( server.addr(), - PROXY_SOURCE, - Assertions::AppendForwarded { - host: "public.example", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "public.example", "https")), false, ); let response = raw_request( @@ -800,10 +777,10 @@ mod tests { ), ); let value = response_json(&response); - let trusted = networks != "127.0.0.3/32"; + let trusted = networks != "127.0.0.0/32"; assert_metadata( &value, - Some(if trusted { "127.0.0.1" } else { "127.0.0.2" }), + Some(if trusted { "192.0.2.1" } else { "127.0.0.1" }), if trusted { "public.example" } else { @@ -816,7 +793,7 @@ mod tests { "untrusted_peer" }, ); - assert_peer_ip(&value, PROXY_SOURCE); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); assert_no_diagnostic_headers(&response); server.signal("TERM"); assert!(server.wait().success()); @@ -826,12 +803,13 @@ mod tests { #[test] fn native_two_proxy_chain_stops_at_untrusted_hop_and_gateway_replaces_prefix() { - if !require_proxy_sources("native two-proxy test", &[PROXY_SOURCE, INGRESS_SOURCE]) { - return; - } + // The ingress is the server's real 127.0.0.1 peer. It reports the first proxy as + // 192.0.2.2, and the first proxy reports the visitor, so the chain has three + // distinct hops: 198.51.100.99 (visitor-supplied), 192.0.2.1, then 192.0.2.2. + let first_proxy = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2)); for (networks, boundary) in [ - ("127.0.0.2/32,127.0.0.3/32", "127.0.0.1"), - ("127.0.0.3/32", "127.0.0.2"), + ("127.0.0.1/32,192.0.2.2/32", "192.0.2.1"), + ("127.0.0.1/32", "192.0.2.2"), ] { let roots = Roots::new(); let addr = address(); @@ -842,20 +820,12 @@ mod tests { server.ready(); let ingress = LocalProxy::start( server.addr(), - INGRESS_SOURCE, - Assertions::AppendForwarded { - host: "final.example", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(first_proxy, "final.example", "https")), false, ); let first = LocalProxy::start( ingress.addr(), - PROXY_SOURCE, - Assertions::AppendForwarded { - host: "earlier.example", - scheme: "http", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "earlier.example", "http")), false, ); let value = response_json(&raw_request( @@ -866,7 +836,7 @@ mod tests { )); assert_metadata(&value, Some(boundary), "final.example", "https", "accepted"); assert_eq!(value["handler"]["host_source"], "trusted_forwarded"); - assert_peer_ip(&value, INGRESS_SOURCE); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); server.signal("TERM"); assert!(server.wait().success()); assert_final_zero(&server); @@ -874,13 +844,12 @@ mod tests { let roots = Roots::new(); let addr = address(); let mut server = Server::spawn( - native_command("diagnostics", &roots, addr, "127.0.0.3/32", "forwarded"), + native_command("diagnostics", &roots, addr, "127.0.0.1/32", "forwarded"), addr, ); server.ready(); let gateway = LocalProxy::start( server.addr(), - INGRESS_SOURCE, Assertions::ReplaceForwarded { client: "203.0.113.7".parse().expect("verified gateway client"), host: "gateway.example", @@ -907,17 +876,17 @@ mod tests { } fn assert_missing_unresolved_and_duplicate_family(addr: SocketAddr, family: &str) { - // This source-bound relay preserves deliberate bad inputs rather than sanitizing them. - let gateway = LocalProxy::start(addr, PROXY_SOURCE, Assertions::Preserve, false); + // This trusted relay preserves deliberate bad inputs rather than sanitizing them. + let gateway = LocalProxy::start(addr, Assertions::Preserve, false); let absent = response_json(&raw_request(gateway.addr(), &metadata_request(""))); assert_metadata( &absent, - Some("127.0.0.2"), + Some("127.0.0.1"), "direct.example:8080", "http", "absent", ); - assert_peer_ip(&absent, PROXY_SOURCE); + assert_peer_ip(&absent, Ipv4Addr::LOCALHOST, addr); assert_eq!(absent["handler"]["client_source"], "direct"); let without_address = if family == "forwarded" { @@ -934,7 +903,7 @@ mod tests { if family == "forwarded" { None } else { - Some("127.0.0.2") + Some("127.0.0.1") }, "partial.example", "https", @@ -944,22 +913,23 @@ mod tests { "partial" }, ); - assert_peer_ip(&missing_client, PROXY_SOURCE); + assert_peer_ip(&missing_client, Ipv4Addr::LOCALHOST, addr); for headers in [ if family == "forwarded" { "Forwarded: for=unknown;host=gap.example;proto=https\r\n" } else { "X-Forwarded-For: unknown\r\nX-Forwarded-Host: gap.example\r\nX-Forwarded-Proto: https\r\n" }, + // The only hop is the trusted peer itself, so the walk exhausts the chain. if family == "forwarded" { - "Forwarded: for=127.0.0.2;host=gap.example;proto=https\r\n" + "Forwarded: for=127.0.0.1;host=gap.example;proto=https\r\n" } else { - "X-Forwarded-For: 127.0.0.2\r\nX-Forwarded-Host: gap.example\r\nX-Forwarded-Proto: https\r\n" + "X-Forwarded-For: 127.0.0.1\r\nX-Forwarded-Host: gap.example\r\nX-Forwarded-Proto: https\r\n" }, ] { let value = response_json(&raw_request(gateway.addr(), &metadata_request(headers))); assert_metadata(&value, None, "gap.example", "https", "unresolved_chain"); - assert_peer_ip(&value, PROXY_SOURCE); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, addr); let source = if family == "forwarded" { "trusted_forwarded" } else { @@ -982,39 +952,31 @@ mod tests { "http", "malformed", ); - assert_peer_ip(&malformed_duplicate, PROXY_SOURCE); + assert_peer_ip(&malformed_duplicate, Ipv4Addr::LOCALHOST, addr); } #[test] fn native_selected_families_conflicts_malformed_sets_gaps_and_exhaustion() { - if !require_proxy_sources("native forwarding-family test", &[PROXY_SOURCE]) { - return; - } for family in ["forwarded", "x-forwarded"] { let roots = Roots::new(); let addr = address(); let mut server = Server::spawn( - native_command("diagnostics", &roots, addr, "127.0.0.2/32", family), + native_command("diagnostics", &roots, addr, "127.0.0.1/32", family), addr, ); server.ready(); + let hop = Hop::new(VISITOR, "selected.example", "https"); let assertions = if family == "forwarded" { - Assertions::AppendForwarded { - host: "selected.example", - scheme: "https", - } + Assertions::AppendForwarded(hop) } else { - Assertions::AppendXForwarded { - host: "selected.example", - scheme: "https", - } + Assertions::AppendXForwarded(hop) }; - let proxy = LocalProxy::start(server.addr(), PROXY_SOURCE, assertions, false); + let proxy = LocalProxy::start(server.addr(), assertions, false); for (prefix, expected_result, client, host, scheme) in [ ( "Forwarded: for=198.51.100.1;host=wrong.example;proto=http\r\nX-Forwarded-For: 203.0.113.1\r\nX-Forwarded-Host: wrong.example\r\nX-Forwarded-Proto: http\r\n", "accepted", - Some("127.0.0.1"), + Some("192.0.2.1"), "selected.example", "https", ), @@ -1026,7 +988,7 @@ mod tests { "X-Forwarded-For: bad-address\r\n" }, "accepted", - Some("127.0.0.1"), + Some("192.0.2.1"), "selected.example", "https", ), @@ -1037,14 +999,14 @@ mod tests { "X-Forwarded-For: unknown\r\n" }, "accepted", - Some("127.0.0.1"), + Some("192.0.2.1"), "selected.example", "https", ), ] { let value = response_json(&raw_request(proxy.addr(), &metadata_request(prefix))); assert_metadata(&value, client, host, scheme, expected_result); - assert_peer_ip(&value, PROXY_SOURCE); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); } assert_missing_unresolved_and_duplicate_family(server.addr(), family); server.signal("TERM"); @@ -1066,23 +1028,16 @@ mod tests { #[test] fn native_verified_tls_ingress_overwrites_public_assertions_and_rejects_wrong_name() { - if !require_proxy_sources("native verified TLS test", &[PROXY_SOURCE]) { - return; - } let roots = Roots::new(); let addr = address(); let mut server = Server::spawn( - native_command("diagnostics", &roots, addr, "127.0.0.2/32", "forwarded"), + native_command("diagnostics", &roots, addr, "127.0.0.1/32", "forwarded"), addr, ); server.ready(); let proxy = LocalProxy::start( server.addr(), - PROXY_SOURCE, - Assertions::AppendForwarded { - host: "native-proxy.test", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "native-proxy.test", "https")), true, ); let request = metadata_request( @@ -1093,7 +1048,7 @@ mod tests { let value = response_json(&response); assert_metadata( &value, - Some("127.0.0.1"), + Some("192.0.2.1"), "native-proxy.test", "https", "accepted", @@ -1962,7 +1917,7 @@ mod tests { "https", "accepted", ); - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); server.signal(shutdown); assert!(server.wait().success(), "{}", server.log()); diff --git a/crates/edgezero-adapter-spin/src/after_response.rs b/crates/edgezero-adapter-spin/src/after_response.rs new file mode 100644 index 000000000..8034a7e66 --- /dev/null +++ b/crates/edgezero-adapter-spin/src/after_response.rs @@ -0,0 +1,84 @@ +//! Spin's after-response capability error. +//! +//! Spin does not run after-response tasks. Every converted request carries a rejecting scheduler. +//! Core first checks the budget and task limit; zero or over-limit budgets return `500`. +//! Registrations that pass those checks reach the scheduler and receive a `501` naming Spin, +//! instead of core's generic error. + +use std::time::Duration; + +use edgezero_core::after_response::{AfterResponseHandle, AfterResponseScheduler}; +use edgezero_core::error::EdgeError; +use futures_util::future::LocalBoxFuture; + +struct SpinAfterResponseUnsupported; + +impl AfterResponseScheduler for SpinAfterResponseUnsupported { + #[inline] + fn schedule( + &self, + _budget: Duration, + task: LocalBoxFuture<'static, ()>, + ) -> Result<(), EdgeError> { + drop(task); + Err(EdgeError::not_implemented( + crate::AFTER_RESPONSE_UNSUPPORTED, + )) + } +} + +/// Installs Spin's capability error after core's budget and task-limit checks pass. +pub(crate) fn unsupported_handle() -> AfterResponseHandle { + AfterResponseHandle::new(SpinAfterResponseUnsupported) +} + +#[cfg(test)] +mod tests { + use super::unsupported_handle; + use crate::AFTER_RESPONSE_UNSUPPORTED; + use edgezero_core::http::StatusCode; + use std::cell::Cell; + use std::rc::Rc; + use std::time::Duration; + + struct DropProbe(Rc>); + + #[expect( + clippy::missing_trait_methods, + reason = "`Drop::pin_drop` is unstable (`pin_ergonomics`) and conflicts with `drop`" + )] + impl Drop for DropProbe { + fn drop(&mut self) { + self.0.set(true); + } + } + + #[test] + fn registration_reports_spin_capability_error_and_drops_task_unpolled() { + let polled = Rc::new(Cell::new(false)); + let dropped = Rc::new(Cell::new(false)); + let probe = DropProbe(Rc::clone(&dropped)); + let observed = Rc::clone(&polled); + + let error = unsupported_handle() + .schedule(Duration::from_secs(1), async move { + let _probe = probe; + observed.set(true); + }) + .unwrap_err(); + + assert_eq!(error.status(), StatusCode::NOT_IMPLEMENTED); + assert_eq!(error.message(), AFTER_RESPONSE_UNSUPPORTED); + assert!(!polled.get(), "a rejected task is never polled"); + assert!(dropped.get(), "a rejected task is dropped at registration"); + } + + #[test] + fn zero_budget_is_a_programming_error_before_the_capability_error() { + let error = unsupported_handle() + .schedule(Duration::ZERO, async {}) + .unwrap_err(); + + assert_eq!(error.status(), StatusCode::INTERNAL_SERVER_ERROR); + } +} diff --git a/crates/edgezero-adapter-spin/src/lib.rs b/crates/edgezero-adapter-spin/src/lib.rs index 47dfbeefa..efe91f77e 100644 --- a/crates/edgezero-adapter-spin/src/lib.rs +++ b/crates/edgezero-adapter-spin/src/lib.rs @@ -1,5 +1,7 @@ //! Adapter helpers for Spin (Fermyon). +#[cfg(any(test, all(feature = "spin", target_arch = "wasm32")))] +mod after_response; #[cfg(all(feature = "cli", not(target_arch = "wasm32")))] pub mod cli; @@ -80,6 +82,11 @@ pub const AKAMAI_FUNCTIONS_PLATFORM: edgezero_core::PlatformMetadata = ), ); +/// Message of Spin's rejecting after-response scheduler's `501 Not Implemented` error. +/// Core checks the budget and task limit before calling that scheduler. +pub const AFTER_RESPONSE_UNSUPPORTED: &str = + "after-response tasks are not supported by the Spin adapter"; + /// Generic Spin resource limits and accounting are runtime-configured. pub const SPIN_PLATFORM: edgezero_core::PlatformMetadata = edgezero_core::PlatformMetadata::new( edgezero_core::PlatformFact::unknown(edgezero_core::PlatformUnknownReason::RuntimeConfigured), diff --git a/crates/edgezero-adapter-spin/src/request.rs b/crates/edgezero-adapter-spin/src/request.rs index 231531a07..b71312b8e 100644 --- a/crates/edgezero-adapter-spin/src/request.rs +++ b/crates/edgezero-adapter-spin/src/request.rs @@ -10,6 +10,7 @@ pub(crate) mod test_support; use crate::SpinResponse; +use crate::after_response::unsupported_handle; use crate::config_store::SpinConfigStore; use crate::context::{SpinRequestContext, context_from_headers, direct_ingress_client_info}; use crate::geo::{SpinClientSource, ingress::capture_inputs}; @@ -151,6 +152,7 @@ fn into_core_request_head(parts: RequestParts, outbound_clock: MonotonicClock) - request .extensions_mut() .insert(outbound_client(outbound_clock)); + request.extensions_mut().insert(unsupported_handle()); request } diff --git a/crates/edgezero-adapter-spin/tests/contract.rs b/crates/edgezero-adapter-spin/tests/contract.rs index 5b77c895a..d0e4d4994 100644 --- a/crates/edgezero-adapter-spin/tests/contract.rs +++ b/crates/edgezero-adapter-spin/tests/contract.rs @@ -1475,6 +1475,65 @@ mod tests { }); } + #[test] + fn native_request_after_response_registration_reports_spin_capability_error() { + sdk_block_on(async { + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let handler_polls = Arc::clone(&polls); + let handler_drops = Arc::clone(&drops); + let router = RouterService::builder() + .get("/task", move |ctx: RequestContext| { + let task_polls = Arc::clone(&handler_polls); + let probe = DropSignal(Arc::clone(&handler_drops)); + async move { + let error = ctx + .after_response(Duration::from_secs(1), async move { + let _probe = probe; + task_polls.fetch_add(1, Ordering::SeqCst); + }) + .expect_err("Spin must reject after-response tasks"); + Ok::<_, EdgeError>(format!( + "{} {}", + error.status().as_u16(), + error.message() + )) + } + }) + .get("/control", |_ctx: RequestContext| async { + Ok::<_, EdgeError>("control") + }) + .build(); + let app = App::new(router); + + for (path, expected) in [ + ( + "/task", + format!("501 {}", edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED), + ), + ("/control", "control".to_owned()), + ] { + let outgoing_request = SpinRequest::builder() + .method("GET") + .uri(format!("http://example.test{path}")) + .body(http_body_util::Empty::::new()) + .expect("outgoing-compatible request"); + let wasi_request = outgoing_request.into_request().expect("WASI request"); + let incoming_request = + SpinRequest::from_request(wasi_request).expect("incoming Spin request"); + + let mut response = dispatch_request(&app, incoming_request) + .await + .expect("Spin response"); + + assert_eq!(response.response_mut().status(), StatusCode::OK); + assert_eq!(captured_body(response).as_ref(), expected.as_bytes()); + } + assert_eq!(polls.load(Ordering::SeqCst), 0, "task must never be polled"); + assert_eq!(drops.load(Ordering::SeqCst), 1, "task must be dropped"); + }); + } + struct CountingMiddleware(Arc); #[async_trait::async_trait(?Send)] diff --git a/crates/edgezero-cli/tests/celld_generated_proof.rs b/crates/edgezero-cli/tests/celld_generated_proof.rs index 61e913d54..5d286a4ab 100644 --- a/crates/edgezero-cli/tests/celld_generated_proof.rs +++ b/crates/edgezero-cli/tests/celld_generated_proof.rs @@ -14,6 +14,7 @@ mod tests { reason = "keep fixture ownership, generated source and proof steps together" )] + use edgezero_core::test_net::accept_blocking; use std::collections::BTreeMap; use std::env; #[cfg(target_os = "linux")] @@ -82,7 +83,7 @@ mod tests { ); let worker = thread::spawn(move || { while !worker_stop.load(Ordering::Relaxed) { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback()); stream diff --git a/crates/edgezero-cli/tests/dynamodb_generated_proof.rs b/crates/edgezero-cli/tests/dynamodb_generated_proof.rs index 2e264f082..e2e649672 100644 --- a/crates/edgezero-cli/tests/dynamodb_generated_proof.rs +++ b/crates/edgezero-cli/tests/dynamodb_generated_proof.rs @@ -7,11 +7,6 @@ //! fixture with dummy credentials and a cleared child environment. Serialize builds that share //! `EDGEZERO_GENERATED_TEST_TARGET_DIR`. -#[cfg(test)] -#[cfg(unix)] -#[path = "support/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] mod tests { #[cfg(unix)] @@ -21,7 +16,7 @@ mod tests { reason = "group test fixture types and their protocol helpers by responsibility" )] - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::collections::BTreeMap; use std::env; use std::fs; diff --git a/crates/edgezero-cli/tests/native_store_generated_proof.rs b/crates/edgezero-cli/tests/native_store_generated_proof.rs index e2d09a7f0..384d61cc3 100644 --- a/crates/edgezero-cli/tests/native_store_generated_proof.rs +++ b/crates/edgezero-cli/tests/native_store_generated_proof.rs @@ -20,15 +20,10 @@ //! `EDGEZERO_GENERATED_TEST_TARGET_DIR` can select a shared target directory; otherwise builds //! use the generated project's `target/`. Serialize builds that share a target directory. -#[cfg(test)] -#[cfg(unix)] -#[path = "support/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] #[cfg(unix)] mod tests { - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::env::var_os; use std::fs; use std::io::{ErrorKind, Read as _, Write as _}; diff --git a/crates/edgezero-cli/tests/support/blocking_accept.rs b/crates/edgezero-cli/tests/support/blocking_accept.rs deleted file mode 100644 index 2eb24b00c..000000000 --- a/crates/edgezero-cli/tests/support/blocking_accept.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! Accept helper for test fixtures that poll a non-blocking std listener. - -use std::io; -use std::net::{SocketAddr, TcpListener, TcpStream}; - -/// Accepts one connection and returns its stream in blocking mode. -/// -/// Fixtures make the listener non-blocking so their accept loop can poll a deadline or stop -/// flag. macOS `accept(2)` copies `O_NONBLOCK` to the accepted socket (Linux does not), so a -/// read on the returned stream would otherwise fail with `WouldBlock` at once instead of -/// honouring its read timeout. `WouldBlock` from `accept` itself is still returned to the caller. -#[inline] -pub(crate) fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { - let (stream, peer) = listener.accept()?; - stream.set_nonblocking(false)?; - Ok((stream, peer)) -} - -#[cfg(test)] -mod tests { - use super::accept_blocking; - use std::io::{ErrorKind, Read as _}; - use std::net::{TcpListener, TcpStream}; - use std::thread; - use std::time::{Duration, Instant}; - - #[test] - fn stream_accepted_from_nonblocking_listener_waits_for_read_timeout() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); - listener - .set_nonblocking(true) - .expect("nonblocking listener"); - let address = listener.local_addr().expect("listener address"); - let _client = TcpStream::connect(address).expect("connect loopback client"); - let deadline = Instant::now() - .checked_add(Duration::from_secs(2)) - .expect("deadline fits the monotonic clock"); - let (mut stream, _peer) = loop { - match accept_blocking(&listener) { - Ok(accepted) => break accepted, - Err(error) if error.kind() == ErrorKind::WouldBlock => { - assert!( - Instant::now() < deadline, - "loopback connection was not queued" - ); - thread::sleep(Duration::from_millis(5)); - } - Err(error) => panic!("accept failed: {error}"), - } - }; - stream - .set_read_timeout(Some(Duration::from_millis(200))) - .expect("read timeout"); - let started = Instant::now(); - let error = stream - .read(&mut [0_u8; 1]) - .expect_err("the client sent nothing"); - let waited = started.elapsed(); - assert!( - matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut), - "unexpected read error: {error}" - ); - assert!( - waited >= Duration::from_millis(150), - "read returned after {waited:?}, before its 200 ms timeout" - ); - } -} diff --git a/crates/edgezero-core/src/after_response.rs b/crates/edgezero-core/src/after_response.rs index 5d4e387de..1244f4e87 100644 --- a/crates/edgezero-core/src/after_response.rs +++ b/crates/edgezero-core/src/after_response.rs @@ -4,7 +4,10 @@ //! The task becomes eligible once the request's response attempt ends at the adapter's terminal //! egress boundary, and its budget starts at that point. Once the budget expires, the adapter //! cancels the task before its next poll; it cannot interrupt a running poll. Adapters without -//! support install no handle, so registration fails with [`EdgeError::NotImplemented`]. +//! support install either no handle or one that rejects every task. Without a handle, +//! registration returns [`EdgeError::NotImplemented`] for any budget. An installed handle first +//! checks the budget and task limit, returning an internal error if either is invalid. A +//! rejecting scheduler returns [`EdgeError::NotImplemented`] after those checks pass. use std::fmt; use std::future::poll_fn; @@ -18,7 +21,8 @@ use futures_util::future::LocalBoxFuture; use crate::error::EdgeError; -/// Message returned when the adapter installed no after-response scheduler for the request. +/// Message returned when no after-response scheduler is installed for the request. Adapters that +/// install a rejecting scheduler may use their own message. pub const AFTER_RESPONSE_UNSUPPORTED: &str = "after-response tasks are not supported by this adapter"; diff --git a/crates/edgezero-core/src/context.rs b/crates/edgezero-core/src/context.rs index 0a8f4645a..a1134a057 100644 --- a/crates/edgezero-core/src/context.rs +++ b/crates/edgezero-core/src/context.rs @@ -358,12 +358,14 @@ impl RequestContext { /// request's scope. /// /// # Errors - /// Returns [`EdgeError::NotImplemented`] when the adapter does not support after-response - /// tasks. Returns an internal error for a zero `budget`, a `budget` above - /// [`MAX_AFTER_RESPONSE_BUDGET`](crate::after_response::MAX_AFTER_RESPONSE_BUDGET), once the + /// Without an installed handle, returns [`EdgeError::NotImplemented`] for any budget. + /// An installed handle first returns an internal error for a zero `budget`, a `budget` above + /// [`MAX_AFTER_RESPONSE_BUDGET`](crate::after_response::MAX_AFTER_RESPONSE_BUDGET), or once the /// request registered - /// [`MAX_AFTER_RESPONSE_TASKS`](crate::after_response::MAX_AFTER_RESPONSE_TASKS) tasks, or - /// for the adapter's scheduling error. The task is dropped unpolled on error. + /// [`MAX_AFTER_RESPONSE_TASKS`](crate::after_response::MAX_AFTER_RESPONSE_TASKS) tasks. If those + /// checks pass, returns the adapter's scheduling error, including + /// [`EdgeError::NotImplemented`] from an unsupported scheduler. The task is dropped unpolled + /// on error. #[inline] pub fn after_response(&self, budget: Duration, task: F) -> Result<(), EdgeError> where diff --git a/crates/edgezero-core/src/lib.rs b/crates/edgezero-core/src/lib.rs index c6212fcb1..3ff313bbe 100644 --- a/crates/edgezero-core/src/lib.rs +++ b/crates/edgezero-core/src/lib.rs @@ -57,6 +57,9 @@ pub mod store_registry; /// module docs. Enable via the `test-utils` feature in `[dev-dependencies]`. #[cfg(any(test, feature = "test-utils"))] pub mod test_env; +/// Native socket helpers for cross-crate test fixtures. +#[cfg(all(not(target_arch = "wasm32"), any(test, feature = "test-utils")))] +pub mod test_net; pub mod time; pub use body::{Body, BodyPayload, BodyStream}; diff --git a/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs b/crates/edgezero-core/src/test_net.rs similarity index 93% rename from crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs rename to crates/edgezero-core/src/test_net.rs index 2eb24b00c..e36c5b3aa 100644 --- a/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs +++ b/crates/edgezero-core/src/test_net.rs @@ -5,12 +5,16 @@ use std::net::{SocketAddr, TcpListener, TcpStream}; /// Accepts one connection and returns its stream in blocking mode. /// +/// # Errors +/// +/// Returns the listener accept error or an error restoring blocking mode. +/// /// Fixtures make the listener non-blocking so their accept loop can poll a deadline or stop /// flag. macOS `accept(2)` copies `O_NONBLOCK` to the accepted socket (Linux does not), so a /// read on the returned stream would otherwise fail with `WouldBlock` at once instead of /// honouring its read timeout. `WouldBlock` from `accept` itself is still returned to the caller. #[inline] -pub(crate) fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { +pub fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { let (stream, peer) = listener.accept()?; stream.set_nonblocking(false)?; Ok((stream, peer)) diff --git a/crates/edgezero-store-aws/src/dynamodb_records_tests.rs b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs index 5138b58a5..7d26d2361 100644 --- a/crates/edgezero-store-aws/src/dynamodb_records_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs @@ -10,6 +10,7 @@ use super::*; use crate::dynamodb_kv::sdk_tests::{active_table, loopback_client, read_request}; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits}; use edgezero_core::record_store::{RecordKeyLayout, contract}; +use edgezero_core::test_net::accept_blocking; use edgezero_core::time::MonotonicClock; use serde_json::{Value, json}; use std::collections::{BTreeMap, BTreeSet, VecDeque}; @@ -77,7 +78,7 @@ impl Fixture { let worker_stopped = Arc::clone(&stopped); let worker = thread::spawn(move || { while !worker_stopped.load(Ordering::Acquire) { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, _)) => { stream .set_read_timeout(Some(Duration::from_secs(3))) diff --git a/crates/edgezero-store-aws/src/dynamodb_tests.rs b/crates/edgezero-store-aws/src/dynamodb_tests.rs index 037e2113d..7e28caec4 100644 --- a/crates/edgezero-store-aws/src/dynamodb_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_tests.rs @@ -12,6 +12,7 @@ use super::*; use crate::preparation::AwsPreparation; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits, DynamoDbKvSettings}; +use edgezero_core::test_net::accept_blocking; use edgezero_core::time::MonotonicClock; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::io::{ErrorKind, Read as _, Write as _}; @@ -144,7 +145,7 @@ impl DynamoFixture { let worker_accepted = Arc::clone(&accepted); let worker = thread::spawn(move || { while !worker_stopped.load(Ordering::Acquire) { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, _)) => { worker_accepted.fetch_add(1, Ordering::Relaxed); stream.set_nonblocking(false).expect("blocking stream"); diff --git a/crates/edgezero-store-aws/src/secrets_manager.rs b/crates/edgezero-store-aws/src/secrets_manager.rs index eeba4009a..b98bc4dbc 100644 --- a/crates/edgezero-store-aws/src/secrets_manager.rs +++ b/crates/edgezero-store-aws/src/secrets_manager.rs @@ -148,10 +148,16 @@ impl AwsPreparation { .operation_timeout(operation_budget) .operation_attempt_timeout(attempt_budget) .build(); + let customized_request = request.customize(); + #[cfg(test)] + #[expect( + clippy::shadow_reuse, + reason = "test-only instrumentation keeps the production request path included in test builds" + )] + let customized_request = customized_request.interceptor(tests::SdkExecutionProbe); let result = timeout( operation_budget, - request - .customize() + customized_request .config_override( aws_sdk_secretsmanager::Config::builder().timeout_config(per_operation), ) @@ -197,6 +203,8 @@ impl AwsPreparation { } fn classify_operation_error(error: &SdkError) -> PreparationError { + #[cfg(test)] + tests::record_attempt_timeout(error); if matches!(error, SdkError::TimeoutError(_)) || matches!(error, SdkError::DispatchFailure(failure) if failure.is_timeout()) { @@ -307,16 +315,53 @@ mod tests { use aws_sdk_secretsmanager::operation::get_secret_value::GetSecretValueOutput; use aws_sdk_secretsmanager::primitives::Blob; use bytes::Bytes; + use edgezero_core::test_net::accept_blocking; use std::io::{Error as IoError, ErrorKind}; use std::io::{Read as _, Write as _}; use std::net::{TcpListener, TcpStream}; use std::process::{Command, Stdio}; - use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::thread; use std::time::{Duration, Instant}; + /// How long the holding fixture waits for the client to abandon an unanswered attempt. + /// This bounds the fixture read after accept; it does not identify the client's timeout + /// cause, since an attempt may already have ended before the fixture accepts it. + const HOLD_BOUND: Duration = Duration::from_secs(5); + const TEST_ARN: &str = "arn:aws:secretsmanager:us-east-1:111122223333:secret:fixture-AbCdEf"; static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + static SDK_EXECUTIONS: AtomicU64 = AtomicU64::new(0); + static OBSERVED_ATTEMPT_TIMEOUT: AtomicBool = AtomicBool::new(false); + + #[derive(Debug)] + pub(super) struct SdkExecutionProbe; + + #[expect( + clippy::missing_trait_methods, + reason = "the execution observer must retain the SDK defaults for every other pipeline hook" + )] + impl aws_sdk_secretsmanager::config::Intercept for SdkExecutionProbe { + fn name(&self) -> &'static str { + "test-sdk-execution-count" + } + + fn read_before_execution( + &self, + _context: &aws_sdk_secretsmanager::config::interceptors::BeforeSerializationInterceptorContextRef<'_>, + _config: &mut aws_sdk_secretsmanager::config::ConfigBag, + ) -> Result<(), aws_smithy_runtime_api::box_error::BoxError> { + SDK_EXECUTIONS.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + } + + /// One connection the SDK opened against `holding_fixture`. + struct HeldConnection { + /// The client closed the connection within `HOLD_BOUND`. + closed_by_client: bool, + } struct LoopbackFixture { listener: TcpListener, @@ -338,7 +383,6 @@ mod tests { #[derive(Clone)] enum FixtureResponse { Decryption, - Delay(Duration), Denied, InternalError, InvalidRequest, @@ -348,6 +392,44 @@ mod tests { Success, } + pub(super) fn record_attempt_timeout( + error: &SdkError, + ) { + if !matches!(error, SdkError::TimeoutError(_)) { + return; + } + // aws-smithy-runtime 1.16.0 exposes no typed kind/duration accessor for its private + // MaybeTimeoutError. Recheck this exact comparison when upgrading the pinned SDK. + // Source text is compared locally and never printed or retained. + let mut source: Option<&dyn std::error::Error> = Some(error); + while let Some(source_error) = source { + if source_error.to_string() + == "operation attempt timeout (single attempt) occurred after 100ms" + { + OBSERVED_ATTEMPT_TIMEOUT.store(true, Ordering::Relaxed); + } + source = source_error.source(); + } + } + + #[expect( + clippy::print_stdout, + reason = "only fixed verified timeout markers reach the parent fixture" + )] + fn report_timeout_evidence() { + assert_eq!( + SDK_EXECUTIONS.load(Ordering::Relaxed), + 1, + "preparation must issue one SDK send; the SDK alone owns retries" + ); + assert!( + OBSERVED_ATTEMPT_TIMEOUT.load(Ordering::Relaxed), + "the pinned SDK must report the exact 100 ms attempt timeout before sanitization" + ); + println!("sdk-executions: 1"); + println!("sdk-attempt-timeout: 100ms"); + } + fn assert_sdk_fixture_scope() { let endpoint = std::env::var("AWS_ENDPOINT_URL_SECRETS_MANAGER").expect("fixture endpoint required"); @@ -364,58 +446,84 @@ mod tests { ); } - fn respond(mut stream: TcpStream, response: FixtureResponse) -> (String, String) { - stream - .set_read_timeout(Some(Duration::from_secs(3))) - .expect("request read timeout"); - let mut request = Vec::new(); - let mut chunk = [0_u8; 4096]; - let header_end = loop { - let read = stream.read(&mut chunk).expect("read request headers"); - assert_ne!(read, 0, "SDK closed before request headers"); - request.extend_from_slice(&chunk[..read]); - if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") { - break end - .checked_add(4) - .expect("header terminator offset fits request"); - } - assert!(request.len() < 64 * 1024, "bounded fixture request headers"); - }; - let headers = String::from_utf8_lossy(&request[..header_end]).to_ascii_lowercase(); - let content_length = headers + /// Decode and validate complete SDK requests; timeout attempts may close before completion. + #[expect( + clippy::unwrap_in_result, + reason = "None means incomplete; malformed fixture requests must fail rather than look incomplete" + )] + fn decode_request(received: &[u8]) -> Option<(String, String)> { + let header_end = received + .windows(4) + .position(|bytes| bytes == b"\r\n\r\n")? + .checked_add(4) + .expect("header offset fits request"); + let headers = String::from_utf8_lossy(&received[..header_end]).to_ascii_lowercase(); + let length = headers .lines() .find_map(|line| line.strip_prefix("content-length:").map(str::trim)) .and_then(|value| value.parse::().ok()) .expect("SDK content length"); let body_end = header_end - .checked_add(content_length) + .checked_add(length) .expect("bounded request body end fits usize"); - while request.len() < body_end { - let read = stream.read(&mut chunk).expect("read request body"); - assert_ne!(read, 0, "SDK closed before request body"); - request.extend_from_slice(&chunk[..read]); - } - let body = String::from_utf8_lossy(&request[header_end..body_end]).into_owned(); + let body = String::from_utf8_lossy(received.get(header_end..body_end)?).into_owned(); assert!(headers.contains("x-amz-target: secretsmanager.getsecretvalue")); assert!( body.contains(TEST_ARN), - "request must contain only the fictional fixture ARN" + "request must contain the fictional fixture ARN" ); - if let FixtureResponse::Delay(delay) = response { - thread::sleep(delay); - let payload = b"{\"SecretString\":\"VALUE_SENTINEL\"}"; - let _header_write = write!( - stream, - "HTTP/1.1 200 OK\r\nContent-Type: application/x-amz-json-1.1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", - payload.len() - ); - let _body_write = stream.write_all(payload); - return (headers, body); - } + Some((headers, body)) + } + + #[test] + fn fixture_decoder_waits_for_complete_headers_and_body() { + let body = serde_json::json!({"SecretId": TEST_ARN}).to_string(); + let head = format!( + "POST / HTTP/1.1\r\nX-Amz-Target: secretsmanager.GetSecretValue\r\nContent-Length: {}\r\n\r\n", + body.len() + ); + assert!(decode_request(b"POST / HTTP/1.1\r\n").is_none()); + assert!(decode_request(head.as_bytes()).is_none()); + let request = format!("{head}{body}"); + let (headers, decoded) = decode_request(request.as_bytes()).expect("complete request"); + assert!(headers.contains("x-amz-target: secretsmanager.getsecretvalue")); + assert_eq!(decoded, body); + } + + #[test] + #[should_panic(expected = "SDK closed before the complete request")] + fn scripted_fixture_rejects_incomplete_request() { + let listener = TcpListener::bind("127.0.0.1:0").expect("fixture listener"); + let mut client = + TcpStream::connect(listener.local_addr().expect("address")).expect("client"); + client + .write_all(b"POST / HTTP/1.1\r\n") + .expect("partial headers"); + client + .shutdown(std::net::Shutdown::Write) + .expect("close incomplete request"); + let (stream, _) = accept_blocking(&listener).expect("accept"); + let _response = respond(stream, FixtureResponse::Success); + } + + fn respond(mut stream: TcpStream, response: FixtureResponse) -> (String, String) { + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("request read timeout"); + let mut request = Vec::new(); + let mut chunk = [0_u8; 4096]; + let (headers, body) = loop { + if let Some(decoded) = decode_request(&request) { + break decoded; + } + let read = stream.read(&mut chunk).expect("read complete SDK request"); + assert_ne!(read, 0, "SDK closed before the complete request"); + request.extend_from_slice(&chunk[..read]); + assert!(request.len() < 64 * 1024, "bounded fixture request"); + }; let (status, code, payload) = match response { FixtureResponse::Decryption => (400_u16, "Bad Request", r#"{"__type":"DecryptionFailure","message":"VALUE_SENTINEL"}"#.to_owned()), FixtureResponse::Denied => (400_u16, "Bad Request", r#"{"__type":"AccessDeniedException","message":"ARN_SENTINEL CREDENTIAL_SENTINEL"}"#.to_owned()), - FixtureResponse::Delay(_) => return (headers, body), FixtureResponse::InternalError => (500_u16, "Internal Server Error", r#"{"__type":"InternalServiceError","message":"SDK_ERROR_SENTINEL"}"#.to_owned()), FixtureResponse::InvalidRequest => (400_u16, "Bad Request", r#"{"__type":"InvalidRequestException","message":"ARN_SENTINEL is scheduled for deletion"}"#.to_owned()), FixtureResponse::Json(payload) => (200_u16, "OK", payload), @@ -431,6 +539,82 @@ mod tests { (headers, body) } + /// Accepts every connection the SDK opens and never answers, so the client's attempt + /// deadline is the only thing that ends each attempt. The deadline runs from the start of + /// the attempt, so a descheduled child can abandon a connection before writing its request; + /// that is recorded as a client-side close, not treated as a fixture failure. + fn holding_fixture() -> ( + String, + Arc, + thread::JoinHandle>, + ) { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind literal loopback only"); + listener + .set_nonblocking(true) + .expect("nonblocking listener"); + let endpoint = format!( + "http://{}", + listener.local_addr().expect("loopback address") + ); + let stop = Arc::new(AtomicBool::new(false)); + let worker_stop = Arc::clone(&stop); + let worker = thread::spawn(move || { + let deadline = Instant::now() + .checked_add(Duration::from_secs(30)) + .expect("fixture deadline fits the monotonic clock"); + let mut held = Vec::new(); + loop { + // Read the flag before accepting: once the child has exited, every connection it + // opened is already queued, so draining until `WouldBlock` counts all of them. + let stopping = worker_stop.load(Ordering::Acquire); + match accept_blocking(&listener) { + Ok((stream, peer)) => { + assert!(peer.ip().is_loopback(), "fixture peer must be loopback"); + held.push(hold(stream)); + } + Err(error) if error.kind() == ErrorKind::WouldBlock => { + if stopping { + break; + } + assert!(Instant::now() < deadline, "SDK child did not finish"); + thread::sleep(Duration::from_millis(5)); + } + Err(error) => panic!("fixture accept failed: {error}"), + } + } + held + }); + (endpoint, stop, worker) + } + + fn hold(mut stream: TcpStream) -> HeldConnection { + stream + .set_read_timeout(Some(HOLD_BOUND)) + .expect("held connection bound"); + let mut received = Vec::new(); + let mut chunk = [0_u8; 4096]; + let closed_by_client = loop { + match stream.read(&mut chunk) { + Ok(0) => break true, + Ok(read) => { + received.extend_from_slice(&chunk[..read]); + assert!(received.len() < 64 * 1024, "bounded held request"); + } + Err(error) if error.kind() == ErrorKind::ConnectionReset => break true, + Err(error) + if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => + { + break false; + } + Err(error) => panic!("held connection read failed: {error}"), + } + }; + // Complete requests are validated identically to scripted responses; an attempt + // that times out before writing its full request remains legitimate. + let _request = decode_request(&received); + HeldConnection { closed_by_client } + } + fn loopback_fixture(responses: Vec) -> (String, LoopbackFixture) { let listener = TcpListener::bind("127.0.0.1:0").expect("bind literal loopback only"); listener @@ -447,7 +631,7 @@ mod tests { let mut bodies = Vec::new(); for response in responses { let stream = loop { - match worker_listener.accept() { + match accept_blocking(&worker_listener) { Ok((stream, peer)) => { assert!(peer.ip().is_loopback(), "fixture peer must be loopback"); break stream; @@ -788,19 +972,32 @@ mod tests { #[test] fn real_sdk_attempt_timeout_is_observed_without_an_outer_retry_loop() { - let (endpoint, fixture) = - loopback_fixture(vec![FixtureResponse::Delay(Duration::from_millis(350))]); + let (endpoint, stop, fixture) = holding_fixture(); let child = isolated_sdk_child(&endpoint, "timeout"); - let requests = fixture.join().expect("fixture thread"); + stop.store(true, Ordering::Release); + let held = fixture.join().expect("fixture thread"); assert!( child.status.success(), "timeout child failed: {}", String::from_utf8_lossy(&child.stderr) ); - assert_eq!( - requests.len(), - 1, - "SDK timeout behavior is inside the one provider operation" + let output = String::from_utf8_lossy(&child.stdout); + assert!( + output.contains("sdk-executions: 1\n"), + "exactly one SDK send is required" + ); + assert!( + output.contains("sdk-attempt-timeout: 100ms\n"), + "the SDK must identify the configured 100 ms attempt timeout" + ); + assert!( + (1..=3).contains(&held.len()), + "only the SDK's own attempts (at most 3) reach the fixture: {} connections", + held.len() + ); + assert!( + held.iter().all(|connection| connection.closed_by_client), + "the SDK must abandon every unanswered fixture connection" ); } @@ -813,6 +1010,10 @@ mod tests { clippy::print_stdout, reason = "the child reports its closed error category to the parent fixture" )] + #[expect( + clippy::too_many_lines, + reason = "one child entry point maps every scripted SDK scenario to its expected outcome" + )] #[tokio::test] async fn sdk_child_entry() { let Ok(scenario) = std::env::var("EDGEZERO_SECRETS_SCENARIO") else { @@ -836,8 +1037,10 @@ mod tests { crate::settings::AwsPreparationLimits { connect_timeout_ms: 50, attempt_timeout_ms: 100, - operation_timeout_ms: 500, - preparation_timeout_ms: 2_000, + // Far beyond the attempt deadline, so only the attempt deadline can end an + // unanswered attempt. + operation_timeout_ms: 10_000, + preparation_timeout_ms: 12_000, ..crate::settings::AwsPreparationLimits::default() } } else { @@ -849,6 +1052,9 @@ mod tests { ) .expect("valid session"); let result = session.prepare_secrets(&settings, "runtime").await; + if scenario == "timeout" { + report_timeout_evidence(); + } match scenario.as_str() { "retry" | "current" | "stage" | "version" | "dedup" => { let handle = result.expect("fixture-backed mapped secret prepares"); diff --git a/docs/guide/adapters/spin.md b/docs/guide/adapters/spin.md index 74d2928f1..9958df206 100644 --- a/docs/guide/adapters/spin.md +++ b/docs/guide/adapters/spin.md @@ -630,6 +630,21 @@ operations invocation-local. Standard response delivery remains lazy under host backpressure; retention adds no whole-response buffer or collection cap. Restore `run_app` and remove the cache to roll back; default generated entry points are unchanged. +## After-response tasks + +Spin does not run after-response tasks. Core checks the budget first: it must be positive and at +most 30 seconds, or registration returns `500`. Registrations that pass reach Spin's scheduler and +return `EdgeError::NotImplemented` (`501`) with the message +`after-response tasks are not supported by the Spin adapter`, exported as +`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`. The task is dropped without being polled. +Every Spin entry point that converts a native request installs this scheduler, including +`run_app`, `dispatch_app` and `request::into_core_request`. Branch on the status or the +`not_implemented` kind rather than the message (core's constant of the same name does not match +on Spin), and do the work inline or elsewhere. An application +that cannot run without the tasks can declare `after-response-tasks` under +`[capabilities] required`, so `edgezero build`, `serve` and `deploy` refuse Spin. See the +[after-response task matrix](/guide/capabilities#after-response-task-matrix). + ## Runtime ingress metadata Conversion captures SDK URI parts before rebuilding the core request. Origin diff --git a/docs/guide/capabilities.md b/docs/guide/capabilities.md index f2fdae81d..623b7c96c 100644 --- a/docs/guide/capabilities.md +++ b/docs/guide/capabilities.md @@ -384,7 +384,11 @@ so CPU-bound or blocking work overruns it. 30 seconds after response completion or disconnect across all `waitUntil` calls; platform CPU/memory limits or earlier termination can shorten execution. Tasks have no persistence or automatic retry. See [Workers context limits](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil). -- Spin installs no scheduler, so registration returns `501 Not Implemented`. +- Spin rejects registrations that pass core's budget and task-limit checks with `501 Not Implemented` + and the message `after-response tasks are not supported by the Spin adapter` + (`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`). The task is dropped without being polled. + Core returns `500` for a zero budget or a budget above 30 seconds before calling the scheduler. A + refused registration does not use one of the 64 task slots, so Spin never reaches the task limit. ## Outbound Matrix diff --git a/docs/guide/handlers.md b/docs/guide/handlers.md index 42010d82d..ddb7894d0 100644 --- a/docs/guide/handlers.md +++ b/docs/guide/handlers.md @@ -362,7 +362,9 @@ async fn page(ctx: RequestContext) -> Result<&'static str, EdgeError> { } ``` -Registration returns `501 Not Implemented` on adapters without support; see the +Without an installed handle, registration returns `501 Not Implemented` for any budget. An +installed handle checks the budget and task limit first, returning `500` for invalid limits; +unsupported schedulers return `501` after those checks pass. See the [after-response task matrix](./capabilities.md#after-response-task-matrix). Declare `after-response-tasks` as a required capability when the work is not optional. Tasks return `()`, so handle and log their own failures. A task cannot register further tasks. On Cloudflare the shared diff --git a/docs/superpowers/plans/2026-11-18-spin-after-response-error.md b/docs/superpowers/plans/2026-11-18-spin-after-response-error.md new file mode 100644 index 000000000..bc92785a6 --- /dev/null +++ b/docs/superpowers/plans/2026-11-18-spin-after-response-error.md @@ -0,0 +1,39 @@ +# Spin after-response capability error — plan + +Design: [`2026-11-18-spin-after-response-error-design.md`](../specs/2026-11-18-spin-after-response-error-design.md). +Issue: #483. Original design base: `feature/476-after-response-tasks` (PR #509). +Current PR base: `feature/478-cloudflare-after-response` (PR #512). + +## Tasks + +1. **Failing tests first.** + - `crates/edgezero-adapter-spin/src/after_response.rs` host unit tests: the handle returns + `501` with `AFTER_RESPONSE_UNSUPPORTED`; the task is never polled and is dropped at + registration (drop probe uses core's `missing_trait_methods` expect pattern); a zero budget + through the Spin handle returns `500`. + - `crates/edgezero-adapter-spin/tests/contract.rs` (`ingress_contract`) wasm32 test: a real + `SpinRequest` dispatched through `test_support::dispatch_request` to a route that registers a + task gets a `501` registration error with the Spin message (the handler echoes status and + message in a `200` body); the task is never polled and is dropped once; a control route on + the same app returns `200`. +2. **Implement.** Define `AFTER_RESPONSE_UNSUPPORTED` ungated in `lib.rs` (no `pub use`, which + the `restriction` lint group denies). Add the module (gated like `ingress`: `any(test, + all(feature = "spin", target_arch = "wasm32"))`), insert the handle in + `into_core_request_head`. +3. **Docs.** `capabilities.md` bullet, `adapters/spin.md` section, `CHANGELOG.md` line, and core's + `after_response` module and constant docs (an unsupported adapter may install a rejecting handle). +4. **Negative control.** Run the contract test with the constant present but without the module, import and + insertion; the wasm32 contract test must fail with the + generic core message. Restore. +5. **Verification.** + - `cargo fmt --all -- --check` + - `cargo clippy --workspace --all-targets --all-features -- -D warnings` + - `cargo test --workspace --all-targets` + - `cargo check --workspace --all-targets --features "fastly cloudflare spin"` + - `cargo check -p edgezero-adapter-spin --target wasm32-wasip2 --features spin` + - Spin wasm clippy (`spin`, `spin,test-utils`) as in `format.yml` + - Spin wasm32 `--test contract --test sdk_resources` under Wasmtime 48.0.2 (the CI sdk-tests phase) + - `node scripts/check_outbound_docs_contract.mjs`; docs `npm run lint && npm run format` + - Runtime: `spin up` (4.1.0) on a scratch copy of `examples/app-demo` outside the repo, with a + route whose task would log `AFTER_TASK_RAN`; expect `501` with the Spin message, no marker + in the logs after 2 s, and an existing route `200`. diff --git a/docs/superpowers/specs/2026-11-17-after-response-tasks-design.md b/docs/superpowers/specs/2026-11-17-after-response-tasks-design.md index 32f3651bb..052c32dd4 100644 --- a/docs/superpowers/specs/2026-11-17-after-response-tasks-design.md +++ b/docs/superpowers/specs/2026-11-17-after-response-tasks-design.md @@ -70,7 +70,7 @@ New `Capability::AfterResponseTasks` (`after-response-tasks`). Applications can ## Cloudflare and Spin -No scheduler is installed, so registration returns the 501 capability error. Their private egress `spawn` hooks stay unchanged. #478 and #483 own the change. +No scheduler is installed, so registration returns the 501 capability error. Their private egress `spawn` hooks stay unchanged. #478 and #483 own the change. (#483 later installs a rejecting Spin scheduler; see `2026-11-18-spin-after-response-error-design.md`.) ## Preservation and acceptance diff --git a/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md b/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md new file mode 100644 index 000000000..124d36a20 --- /dev/null +++ b/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md @@ -0,0 +1,137 @@ +# Spin after-response capability error + +Date: 2026-11-18 +Status: approved for implementation. + +Issue: [#483](https://github.com/IABTechLab/edgezero/issues/483). Original design base: +[PR #509](https://github.com/IABTechLab/edgezero/pull/509) (`feature/476-after-response-tasks`), +which adds `RequestContext::after_response`, the `after-response-tasks` capability, and the +portable `501` returned when no scheduler is installed. The current PR base is +[PR #512](https://github.com/IABTechLab/edgezero/pull/512) (`feature/478-cloudflare-after-response`), +which already installs Cloudflare's scheduler on managed requests. + +## Goal + +A Spin handler that calls `ctx.after_response(budget, task)` within core's registration limits +gets an explicit capability error that names the Spin adapter. The task is never polled and is dropped at registration. Apps that +declare `after-response-tasks` as required are refused for Spin before deployment. + +## Why an explicit error, not support + +The issue fixes the scope: Spin returns a capability error. Spin's request lifecycle gives no +documented guarantee that work continues once the response is complete, and hosted Spin +(Akamai Functions) publishes no post-response execution budget. Running tasks there could drop +them silently, which is the outcome #476 forbids. Real support would need its own design and +platform evidence; it is out of scope. + +## Behavior on the original #509 design base + +Spin installs no `AfterResponseHandle`. Registration falls through to core's generic +`EdgeError::not_implemented("after-response tasks are not supported by this adapter")`. The +capability matrix already reports Spin `Unsupported`, so `required = ["after-response-tasks"]` +already fails for Spin. + +The gap is that the error is implicit. It is indistinguishable from a bare core context or an +adapter that forgot to install a scheduler, and it says nothing about which adapter refused. + +## Contract + +- **Status and kind.** Registration that passes core's budget and task-limit checks on a Spin + request returns `EdgeError::NotImplemented` (HTTP `501`, kind `not_implemented`), unchanged + from the original design base for those inputs. +- **Message.** `after-response tasks are not supported by the Spin adapter`. Defined, with no + cfg gate, as `edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED` in `lib.rs` (beside + `SPIN_PLATFORM`), so host-side app tests can name it too. Applications should branch on the + status or kind, not the message. +- **Task.** Never polled. Dropped before `after_response` returns. +- **Registration limits.** On the original #509 design base, Spin installed no handle, so core's + `schedule_with` returned `501` for any budget. With a handle installed, + `AfterResponseHandle::schedule` first returns `500` for a zero budget, a budget above 30 seconds, + or an exhausted 64-task limit, before calling the scheduler. Refused tasks release their slot. + Cloudflare had no handle on that original base and returned `501` for a zero budget. On the + current #512 base, managed Cloudflare requests have a handle and return `500` for that input. + Bare contexts without a handle continue returning the generic `501` for any budget. +- **Reach.** The handle is installed where every native Spin request becomes a core request + (`into_core_request_head`). That covers `run_app`, `run_app_with_platform`, `dispatch_app`, + `AppExt::dispatch`, `dispatch`, `dispatch_with_kv_label` and the public `into_core_request`. + Not covered, by construction: `send_assembly_error` (no app, no handlers), and the test-utils + `dispatch_ingress_*` bridges, which build the core request with `request_builder()` and already + omit `SpinRequestContext` and ingress metadata. Those keep core's generic `501`. +- **Application-inserted handles.** Spin has no adapter `prepare` hook. Core pre-dispatch hooks, + middleware and handlers can still replace or remove the extension, as on every adapter. A + replacement is the application's explicit choice; a removal falls back to core's generic `501`, + so no task is dropped silently. Neither is guarded. + +## Design + +New host-compilable module `crates/edgezero-adapter-spin/src/after_response.rs`: + +```rust +// lib.rs, ungated +pub const AFTER_RESPONSE_UNSUPPORTED: &str = + "after-response tasks are not supported by the Spin adapter"; + +// after_response.rs, gated any(test, all(feature = "spin", target_arch = "wasm32")) +use edgezero_core::after_response::{AfterResponseHandle, AfterResponseScheduler}; + +struct SpinAfterResponseUnsupported; + +impl AfterResponseScheduler for SpinAfterResponseUnsupported { + fn schedule(&self, _budget: Duration, task: LocalBoxFuture<'static, ()>) + -> Result<(), EdgeError> + { + drop(task); + Err(EdgeError::not_implemented(crate::AFTER_RESPONSE_UNSUPPORTED)) + } +} + +pub(crate) fn unsupported_handle() -> AfterResponseHandle; +``` + +`request::into_core_request_head` inserts `after_response::unsupported_handle()` next to the +existing `SpinRequestContext` and outbound client. + +The module compiles on the host (no `spin_sdk` imports), so its unit tests run under the plain +`cargo test --workspace`. The insertion is covered end to end in `tests/contract.rs` +(`ingress_contract`, `spin,test-utils`, wasm32 under Wasmtime): a real `SpinRequest` goes through +`test_support::dispatch_request`, which shares `into_core_request_head` with the production +funnels. CI runs that suite; it does not run the adapter's wasm32 `--lib` tests, whose binary +imports Spin KV resources that plain Wasmtime does not provide. + +Core changes only in documentation: its module doc and its `AFTER_RESPONSE_UNSUPPORTED` doc no +longer imply that an unsupported adapter installs no handle. No change to other adapters, the CLI +capability matrix, or the manifest. + +## Docs + +- `docs/guide/capabilities.md`: the after-response bullet says Spin installs a rejecting + scheduler that returns `501` naming the Spin adapter; Cloudflare keeps its own sentence. +- `docs/guide/adapters/spin.md`: short "After-response tasks" section. +- `CHANGELOG.md`: under the existing after-response heading, Spin no longer listed as pending + (#483); state the adapter-named `501`. + +## Acceptance and preservation + +| Scenario | Base | Intended | Evidence | +| --- | --- | --- | --- | +| Spin handler registers a task | 501, generic message | registration error is 501 with the Spin message | wasm32 contract test dispatching a real `SpinRequest` (handler echoes status and message in a 200 body); `spin up` probe propagates the error with `?` and observes a 501 response | +| Task registered on Spin | dropped unpolled | dropped unpolled | host unit test with poll and drop probes | +| Zero budget on Spin | 501 (no handle) | 500 | host unit test through the Spin handle | +| Bare core context (no adapter) | 501, generic message | unchanged | existing core unit test | +| `required = ["after-response-tasks"]` on Spin | refused | refused | existing `adapter_capability_matrix_matches_contracts` | +| Existing Spin routes | unchanged | unchanged | existing Spin suites; `spin up` control route | + +Runtime probe (`spin up` 4.1.0, scratch copy of `examples/app-demo`, not committed): a route +registers a task that would log a unique marker and returns the registration error's status and +message. Expect `501` with the Spin message, no marker in the Spin logs after a pause, and an +existing route still `200`. + +A negative control removes the insertion and its import and confirms the wasm32 contract test fails with the +generic message. + +## Out of scope + +- Running after-response tasks on Spin. +- Cloudflare support (#478, PR #512) is supplied by the current base. The CHANGELOG and capability + guide have already been reconciled to retain Cloudflare's support and Spin's unsupported + capability with its installed rejecting scheduler.