pub async fn spawn_graceful_shutdown_handler<Fut>(
shutdown_hook: impl FnOnce() -> Fut + Send + 'static,
)
graceful-shutdown
only.Expand description
Spawns a task that will be execute a provided async closure when the process
receives unix graceful shutdown signals. If the closure takes longer than 500ms
to execute, an unhandled SIGKILL
signal might be received.
You can use this future to execute cleanup or flush related logic prior to runtime shutdown.
This function’s returned future must be resolved prior to lambda_runtime::run()
.
Note that this implicitly also registers and drives a no-op internal extension that subscribes to no events.
This extension will be named _lambda-rust-runtime-no-op-graceful-shutdown-helper
. This extension name
can not be reused by other registered extensions. This is necessary in order to receive graceful shutdown signals.
This extension is cheap to run because it receives no events, but is not zero cost. If you have another extension registered already, you might prefer to manually construct your own graceful shutdown handling without the dummy extension.
For more information on general AWS Lambda graceful shutdown handling, see: https://github.com/aws-samples/graceful-shutdown-with-aws-lambda
§Panics
This function panics if:
- this function is called after
lambda_runtime::run()
- this function is called outside of a context that has access to the tokio i/o
- the no-op extension cannot be registered
- either signal listener panics tokio::signal::unix
§Example
use lambda_runtime::{Error, service_fn, LambdaEvent};
use serde_json::Value;
#[tokio::main]
async fn main() -> Result<(), Error> {
let func = service_fn(func);
let (writer, log_guard) = tracing_appender::non_blocking(std::io::stdout());
lambda_runtime::tracing::init_default_subscriber_with_writer(writer);
let shutdown_hook = || async move {
std::mem::drop(log_guard);
};
lambda_runtime::spawn_graceful_shutdown_handler(shutdown_hook).await;
lambda_runtime::run(func).await?;
Ok(())
}
async fn func(event: LambdaEvent<Value>) -> Result<Value, Error> {
Ok(event.payload)
}