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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@

## Unreleased

### After-Response Tasks (#476)

- Add `RequestContext::after_response(budget, task)` and the adapter-facing
`edgezero_core::after_response::{AfterResponseScheduler, AfterResponseHandle}`. A task becomes
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.
- Add the `after-response-tasks` capability: Axum and Fastly `BoundedCooperative`,
Cloudflare and Spin `Unsupported` (tracked in #478 and #483).
- 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`.

### Portable client info

- Add `RequestContext::client_info()` and `PreDispatchRequest::client_info()`. They return the
Expand Down
326 changes: 326 additions & 0 deletions crates/edgezero-adapter-axum/src/after_response.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,326 @@
//! Axum after-response tasks: spawned on the server's `LocalSet`, released when the response
//! body leaves Hyper, bounded by their budget and drained on shutdown.

use std::sync::Arc;
use std::time::Duration;

use edgezero_core::OutboundScopeOwner;
use edgezero_core::after_response::{
AfterResponseHandle, AfterResponseScheduler, BudgetOutcome, run_within_budget,
};
use edgezero_core::error::EdgeError;
use futures_util::future::LocalBoxFuture;
use tokio::sync::watch;
use tokio::time::{Instant, sleep_until};

use crate::outbound_executor::AxumOutboundExecutorHandle;

/// Counts after-response tasks that were registered but have not yet finished.
#[derive(Clone, Debug)]
pub(crate) struct AfterResponseTracker(Arc<watch::Sender<usize>>);

impl Default for AfterResponseTracker {
fn default() -> Self {
Self(Arc::new(watch::Sender::new(0)))
}
}

impl AfterResponseTracker {
/// Number of tasks still registered.
pub(crate) fn pending(&self) -> usize {
*self.0.borrow()
}

fn register(&self) -> TrackedTask {
self.0.send_modify(|count| *count = count.saturating_add(1));
TrackedTask(self.clone())
}

/// Resolves once every registered task has finished, timed out or been cancelled.
pub(crate) async fn wait_idle(&self) {
let mut idle = self.0.subscribe();
// The sender lives in `self`, so the channel cannot close while this waits.
let _idle = idle.wait_for(|count| *count == 0).await;
}

/// Logs how many registered tasks shutdown is about to cancel, if any.
pub(crate) fn warn_abandoned(&self) {
let abandoned = self.pending();
if abandoned > 0 {
log::warn!("{abandoned} after-response task(s) abandoned at shutdown");
}
}
}

/// Decrements the tracker when its task ends for any reason, including spawn failure.
struct TrackedTask(AfterResponseTracker);

#[expect(
clippy::missing_trait_methods,
reason = "`Drop::pin_drop` is unstable (`pin_ergonomics`) and conflicts with `drop`"
)]
impl Drop for TrackedTask {
fn drop(&mut self) {
self.0
.0
.send_modify(|count| *count = count.saturating_sub(1));
}
}

/// Releases a request's tasks when dropped, which happens when Hyper drops the response body.
///
/// The drop publishes the release time, so every budget starts at release rather than when the
/// executor first reaches the task.
pub(crate) struct AfterResponseRelease(watch::Sender<Option<Instant>>);

#[expect(
clippy::missing_trait_methods,
reason = "`Drop::pin_drop` is unstable (`pin_ergonomics`) and conflicts with `drop`"
)]
impl Drop for AfterResponseRelease {
fn drop(&mut self) {
// `send_replace` stores the time even when no task subscribed.
self.0.send_replace(Some(Instant::now()));
}
}

/// Per-request scheduler installed by the Axum service.
struct AxumAfterResponse {
delivered: watch::Receiver<Option<Instant>>,
executor: AxumOutboundExecutorHandle,
tracker: AfterResponseTracker,
}

impl AfterResponseScheduler for AxumAfterResponse {
fn schedule(
&self,
budget: Duration,
task: LocalBoxFuture<'static, ()>,
) -> Result<(), EdgeError> {
// The registration window closes when the request's tasks are released.
if self.delivered.has_changed().is_err() {
return Err(EdgeError::internal(anyhow::anyhow!(
"after-response tasks can only be registered while the request is handled"
)));
}
let tracked = self.tracker.register();
let mut delivered = self.delivered.clone();
self.executor
.spawn(Box::pin(async move {
let _tracked = tracked;
// The release stores its time just before it closes the channel, so the value
// is readable whether this wait observed the change or the closure.
let observed = delivered
.wait_for(Option::is_some)
.await
.ok()
.and_then(|released| *released);
let released_at = observed
.or_else(|| *delivered.borrow())
.unwrap_or_else(Instant::now);
let deadline = released_at.checked_add(budget).unwrap_or(released_at);
let scope = OutboundScopeOwner::callback();
let outcome = run_within_budget(scope.run(task), sleep_until(deadline), || {
Instant::now() >= deadline
})
.await;
if outcome != BudgetOutcome::Completed {
log::warn!(
"after-response task exceeded its {budget:?} budget and was cancelled"
);
}
}))
.map(|_detached| ())
}
}

/// Creates the scheduler handle for one request and the release that starts its tasks.
pub(crate) fn request_tasks(
executor: AxumOutboundExecutorHandle,
tracker: AfterResponseTracker,
) -> (AfterResponseHandle, AfterResponseRelease) {
let (release, delivered) = watch::channel(None);
let handle = AfterResponseHandle::new(AxumAfterResponse {
delivered,
executor,
tracker,
});
(handle, AfterResponseRelease(release))
}

#[cfg(test)]
mod tests {
use super::{AfterResponseTracker, request_tasks};
use crate::outbound_executor::AxumOutboundExecutor;
use futures_util::future::pending;
use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;
use tokio::task::yield_now;
use tokio::time::{advance, sleep};

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);
}
}

#[tokio::test(flavor = "current_thread")]
async fn tasks_wait_for_release_then_run_and_untrack() {
let mut owner = AxumOutboundExecutor::new();
let tracker = AfterResponseTracker::default();
let (handle, release) = request_tasks(owner.handle(), tracker.clone());
let ran = Rc::new(Cell::new(false));
let observed = Rc::clone(&ran);
handle
.schedule(Duration::from_secs(5), async move { observed.set(true) })
.unwrap();
assert_eq!(tracker.pending(), 1);
owner
.run_until(async {
for _ in 0_u8..8 {
yield_now().await;
}
assert!(!ran.get(), "a task never starts before its release");
drop(release);
tracker.wait_idle().await;
})
.await;
assert!(ran.get());
assert_eq!(tracker.pending(), 0);
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn budget_cancels_a_pending_task() {
let mut owner = AxumOutboundExecutor::new();
let tracker = AfterResponseTracker::default();
let (handle, release) = request_tasks(owner.handle(), tracker.clone());
let dropped = Rc::new(Cell::new(false));
let started = Rc::new(Cell::new(false));
let probe = DropProbe(Rc::clone(&dropped));
let observed = Rc::clone(&started);
handle
.schedule(Duration::from_millis(50), async move {
let _probe = probe;
observed.set(true);
pending::<()>().await;
})
.unwrap();
drop(release);
owner
.run_until(async {
sleep(Duration::from_millis(49)).await;
assert!(started.get(), "the released task starts");
assert!(!dropped.get(), "the task survives within its budget");
tracker.wait_idle().await;
})
.await;
assert!(dropped.get(), "the budget drops the pending task");
assert_eq!(tracker.pending(), 0);
}

#[tokio::test(flavor = "current_thread")]
async fn registration_closes_when_tasks_are_released() {
let owner = AxumOutboundExecutor::new();
let tracker = AfterResponseTracker::default();
let (handle, release) = request_tasks(owner.handle(), tracker.clone());
drop(release);
let polled = Rc::new(Cell::new(false));
let observed = Rc::clone(&polled);
let result = handle.schedule(Duration::from_secs(1), async move { observed.set(true) });
assert!(result.is_err(), "a released request accepts no more tasks");
assert_eq!(tracker.pending(), 0);
assert!(!polled.get());
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn budget_starts_at_release_not_at_registration() {
let mut owner = AxumOutboundExecutor::new();
let tracker = AfterResponseTracker::default();
let (handle, release) = request_tasks(owner.handle(), tracker.clone());
let ran = Rc::new(Cell::new(false));
let observed = Rc::clone(&ran);
handle
.schedule(Duration::from_millis(50), async move {
sleep(Duration::from_millis(10)).await;
observed.set(true);
})
.unwrap();
owner
.run_until(async {
// A slow response outlasts the budget before the task may start.
sleep(Duration::from_millis(100)).await;
drop(release);
tracker.wait_idle().await;
})
.await;
assert!(ran.get(), "the budget is measured from release");
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn a_task_ready_at_its_deadline_is_cancelled_before_it_writes() {
let mut owner = AxumOutboundExecutor::new();
let tracker = AfterResponseTracker::default();
let (handle, release) = request_tasks(owner.handle(), tracker.clone());
let started = Rc::new(Cell::new(false));
let wrote = Rc::new(Cell::new(false));
let observed_start = Rc::clone(&started);
let observed_write = Rc::clone(&wrote);
handle
.schedule(Duration::from_millis(50), async move {
observed_start.set(true);
// Wakes on the same tick as the budget's deadline.
sleep(Duration::from_millis(50)).await;
observed_write.set(true);
})
.unwrap();
drop(release);
owner.run_until(tracker.wait_idle()).await;
assert!(started.get(), "the task started within its budget");
assert!(
!wrote.get(),
"the task is not polled once its deadline passed"
);
assert_eq!(tracker.pending(), 0);
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn a_budget_that_expires_before_the_first_executor_turn_cancels_unpolled() {
let mut owner = AxumOutboundExecutor::new();
let tracker = AfterResponseTracker::default();
let (handle, release) = request_tasks(owner.handle(), tracker.clone());
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);
handle
.schedule(Duration::from_millis(50), async move {
let _probe = probe;
observed.set(true);
})
.unwrap();
drop(release);
// The executor is busy elsewhere: time passes before the task's first turn.
advance(Duration::from_millis(100)).await;
owner.run_until(tracker.wait_idle()).await;
assert!(!polled.get(), "the budget is measured from release");
assert!(dropped.get(), "the expired task is dropped");
assert_eq!(tracker.pending(), 0);
}

#[test]
fn spawn_failure_untracks_the_task() {
let owner = AxumOutboundExecutor::new();
let tracker = AfterResponseTracker::default();
let (handle, _release) = request_tasks(owner.handle(), tracker.clone());
// No Tokio runtime is current, so the executor refuses the spawn.
assert!(handle.schedule(Duration::from_secs(1), async {}).is_err());
assert_eq!(tracker.pending(), 0);
}
}
9 changes: 9 additions & 0 deletions crates/edgezero-adapter-axum/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ struct EdgezeroAxumConfig {
impl Adapter for AxumCliAdapter {
fn capability(&self, capability: Capability) -> CapabilitySupport {
match capability {
Capability::AfterResponseTasks => CapabilitySupport::BoundedCooperative,
Capability::ConfigReadDeadlines
| Capability::OutboundConnectTimeout
| Capability::OutboundFailureDiagnostics
Expand Down Expand Up @@ -919,10 +920,18 @@ mod tests {
}

#[test]
#[expect(
clippy::too_many_lines,
reason = "keep the complete capability data table together"
)]
fn adapter_capability_matrix_matches_contracts() {
let connect = AXUM_ADAPTER.capability(Capability::OutboundConnectTimeout);
assert_eq!(connect, CapabilitySupport::BestEffort);
for (capability, support) in [
(
Capability::AfterResponseTasks,
CapabilitySupport::BoundedCooperative,
),
(
Capability::ConfigReadAllocationBounds,
CapabilitySupport::Unsupported,
Expand Down
Loading