diff --git a/CHANGELOG.md b/CHANGELOG.md index 931fc205..47cfa76c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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`. 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 00000000..c4af7d3e --- /dev/null +++ b/crates/edgezero-adapter-spin/src/after_response.rs @@ -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>); + + #[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 90248d9d..799e857d 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; @@ -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), diff --git a/crates/edgezero-adapter-spin/src/request.rs b/crates/edgezero-adapter-spin/src/request.rs index f6ec0f42..3b40a141 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 37e8bc1a..c73b7b0e 100644 --- a/crates/edgezero-adapter-spin/tests/contract.rs +++ b/crates/edgezero-adapter-spin/tests/contract.rs @@ -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::::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-core/src/after_response.rs b/crates/edgezero-core/src/after_response.rs index 78c3201d..79f64573 100644 --- a/crates/edgezero-core/src/after_response.rs +++ b/crates/edgezero-core/src/after_response.rs @@ -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; @@ -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"; diff --git a/docs/guide/adapters/spin.md b/docs/guide/adapters/spin.md index c5d00385..23aaf753 100644 --- a/docs/guide/adapters/spin.md +++ b/docs/guide/adapters/spin.md @@ -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 diff --git a/docs/guide/capabilities.md b/docs/guide/capabilities.md index 9e5d3f04..bad30807 100644 --- a/docs/guide/capabilities.md +++ b/docs/guide/capabilities.md @@ -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 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 00000000..efa2316f --- /dev/null +++ b/docs/superpowers/plans/2026-11-18-spin-after-response-error.md @@ -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`. 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 3918d809..bc041245 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 @@ -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 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 00000000..8a190f7a --- /dev/null +++ b/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md @@ -0,0 +1,131 @@ +# Spin after-response capability error + +Date: 2026-11-18 +Status: approved for implementation. + +Issue: [#483](https://github.com/IABTechLab/edgezero/issues/483). 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. + +## Goal + +A Spin handler that calls `ctx.after_response(budget, task)` 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. + +## Current behavior on the 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 with a positive budget on any Spin request returns + `EdgeError::NotImplemented` (HTTP `501`, kind `not_implemented`), unchanged from the base. +- **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. +- **Zero budget.** Changes from `501` to `500`. On the base, Spin installed no handle, so core's + `schedule_with` returned `501` before any budget check. With a handle installed, core's + `AfterResponseHandle::schedule` rejects a zero budget with `500` before the scheduler is called. + That is #509's rule for a programming error, and Axum and Fastly already behave this way. + Cloudflare, which still installs no handle, keeps `501` until #478. +- **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 (#478, PR #512). PR #512 edits the same `capabilities.md` bullet and the same + `CHANGELOG.md` capability line, and says Spin installs no scheduler; whichever lands second + rebases that sentence.