pub struct CleanupStack { /* private fields */ }Expand description
Stack of cleanup functions to run after handler completion.
CleanupStack provides generator-style dependency lifecycle management
similar to FastAPI’s yield dependencies. Cleanup functions are registered
during dependency resolution and run in LIFO order after the handler
completes, even on error or panic.
§Example
// Dependency with cleanup
impl FromDependencyWithCleanup for DbConnection {
type Value = DbConnection;
type Error = HttpError;
async fn setup(ctx: &RequestContext, req: &mut Request)
-> Result<(Self::Value, Option<CleanupFn>), Self::Error>
{
let conn = DbPool::get_connection().await?;
let cleanup = {
let conn = conn.clone();
Box::new(move || {
Box::pin(async move {
conn.release().await;
}) as Pin<Box<dyn Future<Output = ()> + Send>>
}) as CleanupFn
};
Ok((conn, Some(cleanup)))
}
}§Cleanup Order
Cleanup functions run in LIFO order (last registered runs first):
Setup order: A -> B -> C
Cleanup order: C -> B -> AThis ensures that dependencies are cleaned up in the reverse order of their setup, maintaining proper resource lifecycle semantics.
Implementations§
Source§impl CleanupStack
impl CleanupStack
Sourcepub fn push(&self, cleanup: CleanupFn)
pub fn push(&self, cleanup: CleanupFn)
Register a cleanup function to run after handler completion.
Cleanup functions are run in LIFO order (last registered runs first).
Sourcepub fn take_cleanups(&self) -> Vec<CleanupFn> ⓘ
pub fn take_cleanups(&self) -> Vec<CleanupFn> ⓘ
Take all cleanup functions for execution.
Returns cleanups in LIFO order (reversed from registration order). After calling this, the stack is empty.
Sourcepub async fn run_cleanups(&self) -> usize
pub async fn run_cleanups(&self) -> usize
Run all cleanup functions in LIFO order.
This consumes all registered cleanup functions. Each cleanup is awaited in sequence. If a cleanup function panics (either during creation or execution), the remaining cleanups are still attempted.
§Returns
The number of cleanup functions that completed successfully.