tower-scope-spawn
tower-scope-spawn is a Tower layer for request-scoped task management. It uses the scope-spawn crate to spawn background tasks that are automatically cancelled when the request is fully handled or the client disconnects.
This is useful for structured concurrency, preventing resource leaks by ensuring that tasks do not outlive the request that spawned them.
How it works
The ScopeSpawnLayer wraps your service. For each incoming request, it:
- Creates a new
scope_spawn::scope::Scope. - Wraps the
Requestin aWithScopestruct, which includes the new scope. - Passes the
WithScope<Request>to your inner service.
When the tower::Service::call future for the request is dropped (e.g., client disconnect), the associated Scope is cancelled, automatically terminating all tasks spawned within it.
Example
The example below shows a tower::Service that spawns a background task. The task's lifecycle is tied to the request.
To run this example:
Then, test the two scenarios in a separate terminal:
-
Normal Completion: The background task finishes because the client waits.
-
Cancellation: The background task is cancelled because the client disconnects early.
# Press Ctrl+C immediately
//! An example of how to use the `ScopeSpawnLayer`.
use Infallible;
use Future;
use Pin;
use Context;
use Poll;
use Duration;
use Bytes;
use BodyExt;
use Empty;
use http1;
use Request;
use Response;
use TokioIo;
use TowerToHyperService;
use TcpListener;
use sleep;
use Service;
use ServiceBuilder;
use ScopeSpawnLayer;
use WithScope;
// A simple tower::Service that processes a request and spawns a background task.
;