Skip to content

Add Token-Aware, Joinable Axum Drain Helper #2274

Closed

Description

@josecelano

SI-10: Token-Aware, Joinable Axum Drain Helper

Roadmap position: Step 6. Additive shared-helper task.

Parent EPIC: #1488

Related issue: #2234

Goal

Add a shared Axum graceful-shutdown helper that accepts an injected CancellationToken, starts connection draining on cancellation, and can be awaited by the server task that owns it. Keep the existing graceful_shutdown(handle, rx_halt, message, address) helper unchanged so current consumers continue to compile and behave as before.

This creates a reusable building block only; it does not migrate the HTTP tracker, REST API, or health-check API to the new helper.

Background

packages/axum-server/src/signals.rs currently has server implementations spawn graceful_shutdown(...) with tokio::task::spawn and discard the returned JoinHandle. The existing helper waits on a shutdown Halted channel or library-level OS signals, starts Handle::graceful_shutdown, and polls connection count.

The Q2 target architecture requires cancellation to flow from an owner to a child component token and completion to flow upward through awaited handles. A detached drain helper prevents the owner from proving drain completion before the server task reports completion.

Scope

In scope

  • Add a token-aware helper beside the existing helper.
  • Accept an injected CancellationToken, Axum Handle, address, message, and a deadline/budget input suitable for later Q4 configuration.
  • Await token cancellation, request Axum graceful shutdown, and return a typed result distinguishing drained from deadline-reached.
  • Make the helper an awaitable future that a server task can await or spawn while retaining its JoinHandle.
  • Add deterministic tests that cancel a token without delivering OS signals.
  • Document the ownership contract for future HTTP, REST API, and health-check component migrations.

Out of scope

  • Migrating existing Axum server consumers to the new helper.
  • Removing or changing Halted, shutdown_signal_with_message, or global_shutdown_signal().
  • Selecting production deadline values or configuration schema (Q4).
  • Exit-code behavior (Q3) and readiness behavior (Q6).

Architecture and Ownership

Related ADR: Supervised cancellation tree.

The API is additive. The legacy Halted helper and callers remain source- and behavior-compatible until migration and deprecation subissues complete. The new helper waits for injected cancellation and reports drain completion; it neither subscribes to OS signals nor creates detached tasks.

Collaborator Responsibility and ownership contract
Application and JobManager Own root cancellation and top-level component futures; never receive the helper's nested task handle.
Migrating server component (SI-11 through SI-13) Own the helper future or retained JoinHandle, coordinate it with the server future, and await it before reporting completion.
Token-aware drain helper Wait for the injected token, request Handle::graceful_shutdown, wait until connections drain or the supplied absolute deadline expires, then return the typed outcome. It spawns no task.
Axum Handle Performs graceful connection draining after the helper requests it.

Normal-path invariant: after cancellation, a component awaits its drain future and does not complete while it still owns that future. Failure/drop-path invariant: before returning, a component joins or deliberately aborts and records its retained child; it never leaks a detached drain controller. The supplied deadline bounds post-cancellation drain wait. After the first passing vertical slice, review that this API and ownership map remain accurate.

Proposed API Shape

Exact type names are implementation decisions, but responsibility must follow this shape:

pub async fn graceful_shutdown_on_cancellation(
    handle: axum_server::Handle<SocketAddr>,
    cancellation_token: CancellationToken,
    message: String,
    address: SocketAddr,
    deadline: Duration,
) -> GracefulShutdownOutcome

The caller owns the returned future or its spawned JoinHandle. The helper must not spawn an unowned background task. A later component migration uses tokio::select! between its server future and its owned drain future, then awaits any remaining owned child before returning its component outcome.

Implementation Plan

ID Task Expected output
T1 Establish helper contract Inspect existing helper and Axum handle behavior; finalize public input and typed outcome without changing the legacy API.
T2 Implement token-aware drain helper Add the awaitable helper with injected token and supplied deadline; do not spawn an unowned task.
T3 Add deterministic helper tests Cover no drain before cancellation, successful drain, and deadline outcome without OS signals; use the write-unit-test workflow and record test-design review.
T4 Verify legacy compatibility Run unchanged focused tests for Axum HTTP, REST API, and health-check consumers; confirm call sites are unchanged.
T5 Perform completion review Complete automated and manual verification, re-review acceptance criteria, and record an implementation-retrospective decision.

Commit T1-T2 after focused validation and ownership review; commit T3 after focused tests and Arrange-Act-Assert review; commit T4-T5 after final validation and completion review. Test-producing work must use the write-unit-test skill and record a prose-first Arrange-Act-Assert review after each passing increment.

Acceptance Criteria

  • Existing graceful_shutdown behavior and public signature are unchanged.
  • A new token-aware helper accepts injected cancellation without subscribing to an OS signal or receiving a shutdown Halted channel.
  • The helper starts Handle::graceful_shutdown only after token cancellation.
  • The helper returns an outcome that distinguishes all connections drained from the drain deadline reached.
  • The helper creates no unowned task; its caller can await it or retain its join handle.
  • Deterministic tests cancel an injected token and cover drained and deadline outcomes without OS signals.
  • Existing HTTP tracker, REST API, and health-check server tests still pass unchanged against the legacy helper.
  • linter all passes.

Verification Plan

Automatic checks

  • Focused axum-server unit tests for the token-aware helper.
  • Existing focused tests for Axum HTTP tracker, REST API, and health-check server packages, proving legacy call-site compatibility.
  • linter all on the stable Rust toolchain.
  • Pre-push checks when preparing the implementation pull request.

Manual verification

ID Scenario Expected result
M1 Inspect helper ownership The implementation takes CancellationToken, has a deadline input, returns a typed outcome, contains no detached tokio::spawn, and every owned drain task can be awaited or retained.
M2 Exercise graceful drain Start a representative Axum server, establish an in-flight connection, cancel its token, and observe the connection finish before the supplied deadline. New connections stop, the in-flight connection drains, and the helper returns the drained outcome.
M3 Exercise deadline outcome Repeat M2 with a connection active past a deliberately small deadline. The helper returns deadline-reached without an OS signal.

Manual verification is mandatory. Record executed commands, toolchain/runtime, output, relevant logs, results, and failures in issue-local manual-verification-evidence.md. Create implementation-retrospective.md for material discoveries, design changes, or deviations; otherwise record why none was needed in the progress log.

Risks and Trade-offs

  • Axum Handle behavior may make fully deterministic drain tests difficult. Isolate outcome policy behind a testable helper boundary and use local server tests only for real handle interaction.
  • Do not select production timeout values prematurely; accept a caller-provided budget and defer configuration defaults to SI-20/Q4.
  • An internally spawning convenience API would obscure lifecycle ownership; expose an awaitable future and make retained handle ownership explicit in later migrations.

Dependencies and Rollback

Follows the additive server lifecycle API from SI-2 and does not depend on migration of any Axum server consumer. Q4 later defines final deadline relationships and configuration; this task only provides a budget input.

This is additive: reverting it removes only the unused new helper and tests, while all existing Axum consumers continue using the unchanged legacy helper.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions