pub struct LifespanScope<T: Send + Sync + 'static> {
pub state: T,
/* private fields */
}Expand description
Scope returned by a lifespan function containing state and cleanup logic.
The lifespan pattern allows sharing state between startup and shutdown phases, which is particularly useful for resources like database connections that need coordinated initialization and cleanup.
§Example
ⓘ
use fastapi_core::app::{App, LifespanScope, LifespanError};
struct DatabasePool { /* ... */ }
impl DatabasePool {
async fn connect(url: &str) -> Result<Self, Error> { /* ... */ }
async fn close(&self) { /* ... */ }
}
let app = App::builder()
.lifespan(|| async {
// Startup: connect to database
let pool = DatabasePool::connect("postgres://localhost/mydb")
.await
.map_err(|e| LifespanError::with_source("failed to connect to database", e))?;
// Clone for the cleanup closure
let pool_for_cleanup = pool.clone();
// Return state + cleanup
Ok(LifespanScope::new(pool)
.on_shutdown(async move {
pool_for_cleanup.close().await;
}))
})
.build();Fields§
§state: TState produced by the lifespan function.
This state is automatically added to the application’s state container
and can be accessed by handlers via the State<T> extractor.
Implementations§
Source§impl<T: Send + Sync + 'static> LifespanScope<T>
impl<T: Send + Sync + 'static> LifespanScope<T>
Sourcepub fn on_shutdown<F>(self, cleanup: F) -> Self
pub fn on_shutdown<F>(self, cleanup: F) -> Self
Sets the cleanup future to run during application shutdown.
The cleanup runs in reverse order relative to other lifespan/shutdown hooks, after all in-flight requests have completed or been cancelled.
§Example
ⓘ
let scope = LifespanScope::new(pool.clone())
.on_shutdown(async move {
pool.close().await;
println!("Database pool closed");
});Trait Implementations§
Auto Trait Implementations§
impl<T> Freeze for LifespanScope<T>where
T: Freeze,
impl<T> !RefUnwindSafe for LifespanScope<T>
impl<T> Send for LifespanScope<T>
impl<T> !Sync for LifespanScope<T>
impl<T> Unpin for LifespanScope<T>where
T: Unpin,
impl<T> !UnwindSafe for LifespanScope<T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, _span: NoopSpan) -> Self
fn instrument(self, _span: NoopSpan) -> Self
Instruments this future with a span (no-op when disabled).
Source§fn in_current_span(self) -> Self
fn in_current_span(self) -> Self
Instruments this future with the current span (no-op when disabled).