Skip to content
Open
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
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@
after the response attempt ends and is cancelled at its budget. Adapters without support return
`501 Not Implemented` at registration.
- 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 rejects after-response tasks with a `501` that names the adapter
(`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`) on every converted request, instead of
core's generic message (#483). A zero budget on Spin now returns `500`, as on Axum and Fastly,
instead of `501`.
- Axum production, `run_app` and `AxumDevServer::run` shutdown now waits for registered after-response tasks within the
existing shutdown grace, after connections drain. Tasks still pending at the grace make the
process exit non-zero with `grace exhausted`.
Expand Down
82 changes: 82 additions & 0 deletions crates/edgezero-adapter-spin/src/after_response.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//! Spin's after-response capability error.
//!
//! Spin does not run after-response tasks. Every converted request carries a scheduler that
//! rejects them with a `501` naming the Spin adapter, 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,
))
}
}

/// Handle inserted into every Spin request so registration fails with the Spin capability error.
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<Cell<bool>>);

#[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);
}
}
7 changes: 7 additions & 0 deletions crates/edgezero-adapter-spin/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -79,6 +81,11 @@ pub const AKAMAI_FUNCTIONS_PLATFORM: edgezero_core::PlatformMetadata =
),
);

/// Message of the `501 Not Implemented` error that `RequestContext::after_response` returns on
/// Spin, which does not run after-response tasks.
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),
Expand Down
2 changes: 2 additions & 0 deletions crates/edgezero-adapter-spin/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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
}
Expand Down
59 changes: 59 additions & 0 deletions crates/edgezero-adapter-spin/tests/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1412,6 +1412,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::<Bytes>::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<AtomicUsize>);

#[async_trait::async_trait(?Send)]
Expand Down
8 changes: 5 additions & 3 deletions crates/edgezero-core/src/after_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
//!
//! A handler registers a task through [`RequestContext::after_response`](crate::context::RequestContext::after_response).
//! The adapter starts it once the request's response attempt has ended at the adapter's terminal
//! egress boundary, and cancels it when its budget runs out. Adapters without support install no
//! handle, so registration fails with [`EdgeError::NotImplemented`].
//! egress boundary, and cancels it when its budget runs out. Adapters without support install
//! either no handle or one that rejects every task, so registration fails with
//! [`EdgeError::NotImplemented`].

use std::fmt;
use std::sync::Arc;
Expand All @@ -13,7 +14,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";

Expand Down
15 changes: 15 additions & 0 deletions docs/guide/adapters/spin.md
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,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. `ctx.after_response(budget, task)` with a positive budget
returns `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.
A zero budget is a programming error and returns `500`, as on every adapter that installs a
scheduler. Every Spin entry point that converts a native request installs this error, 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
Expand Down
5 changes: 4 additions & 1 deletion docs/guide/capabilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,10 @@ 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 every registration with a positive budget 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.
A zero budget returns `500`, as on Axum and Fastly.

## Outbound Matrix

Expand Down
38 changes: 38 additions & 0 deletions docs/superpowers/plans/2026-11-18-spin-after-response-error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# 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. Base branch: `feature/476-after-response-tasks` (PR #509).

## 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`.
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,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

Expand Down
Loading
Loading