Skip to main content

Runtime

Struct Runtime 

Source
pub struct Runtime<S> { /* private fields */ }
Expand description

Lambda runtime executing a handler function on incoming requests.

Middleware can be added to a runtime using the Runtime::layer method in order to execute logic prior to processing the incoming request and/or after the response has been sent back to the Lambda Runtime API.

§Example

use lambda_runtime::{Error, LambdaEvent, Runtime};
use serde_json::Value;
use tower::service_fn;

#[tokio::main]
async fn main() -> Result<(), Error> {
    let func = service_fn(func);
    Runtime::new(func).run().await?;
    Ok(())
}

async fn func(event: LambdaEvent<Value>) -> Result<Value, Error> {
    Ok(event.payload)
}

Implementations§

Source§

impl<F, EventPayload, Response, BufferedResponse, StreamingResponse, StreamItem, StreamError> Runtime<RuntimeApiClientService<RuntimeApiResponseService<CatchPanicService<'_, F>, EventPayload, Response, BufferedResponse, StreamingResponse, StreamItem, StreamError>, PooledClient>>
where F: Service<LambdaEvent<EventPayload>, Response = Response>, F::Future: Future<Output = Result<Response, F::Error>>, F::Error: Into<Diagnostic> + Debug, EventPayload: for<'de> Deserialize<'de>, Response: IntoFunctionResponse<BufferedResponse, StreamingResponse>, BufferedResponse: Serialize, StreamingResponse: Stream<Item = Result<StreamItem, StreamError>> + Unpin + Send + 'static, StreamItem: Into<Bytes> + Send, StreamError: Into<BoxError> + Send + Debug,

Source

pub fn new(handler: F) -> Self

Create a new runtime that executes the provided handler for incoming requests.

In order to start the runtime and poll for events on the Lambda Runtime APIs, you must call Runtime::run.

Note that manually creating a Runtime does not add tracing to the executed handler as is done by super::run. If you want to add the default tracing functionality, call Runtime::layer with a super::layers::TracingLayer.

§Panics

This function panics if required Lambda environment variables are missing (AWS_LAMBDA_FUNCTION_NAME, AWS_LAMBDA_FUNCTION_MEMORY_SIZE, AWS_LAMBDA_FUNCTION_VERSION, AWS_LAMBDA_RUNTIME_API).

Source§

impl<S> Runtime<S>

Source

pub fn layer<L>(self, layer: L) -> Runtime<L::Service>
where L: Layer<S>, L::Service: Service<LambdaInvocation, Response = (), Error = BoxError>,

Add a new layer to this runtime. For an incoming request, this layer will be executed before any layer that has been added prior.

§Example
use lambda_runtime::{layers, Error, LambdaEvent, Runtime};
use serde_json::Value;
use tower::service_fn;

#[tokio::main]
async fn main() -> Result<(), Error> {
    let runtime = Runtime::new(service_fn(echo)).layer(
        layers::TracingLayer::new()
    );
    runtime.run().await?;
    Ok(())
}

async fn echo(event: LambdaEvent<Value>) -> Result<Value, Error> {
    Ok(event.payload)
}
Source§

impl<S> Runtime<S>

Source

pub fn is_snapstart(&self) -> bool

Returns true if the current execution environment has SnapStart enabled.

Source

pub fn register_snapstart_resource( self, resource: Arc<dyn SnapStartResource>, ) -> Self

Register a SnapStartResource whose before_snapshot/after_restore hooks should run around the SnapStart snapshot/restore boundary.

Register resources in dependency order — foundations first (e.g. credentials before the pool that depends on them). The runtime runs before_snapshot in reverse registration order (LIFO) and after_restore in registration order (FIFO), so teardown and rebuild both happen in the correct relative order. See the snapstart module docs for details.

When SnapStart is not enabled, registered resources are never invoked and add no runtime overhead beyond the cost of holding the Arc.

§Example
use lambda_runtime::{Error, LambdaEvent, Runtime, SnapStartResource};
use std::sync::Arc;
use serde_json::Value;
use tower::service_fn;

// Uses the default no-op hooks; override before_snapshot/after_restore as needed.
struct Pool;
impl SnapStartResource for Pool {}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let pool = Arc::new(Pool);
    let runtime = Runtime::new(service_fn(handler))
        .register_snapstart_resource(pool.clone());
    runtime.run().await
}

async fn handler(event: LambdaEvent<Value>) -> Result<Value, Error> {
    Ok(event.payload)
}
Source§

impl<S> Runtime<S>
where S: Service<LambdaInvocation, Response = (), Error = BoxError> + Clone + Send + 'static, S::Future: Send,

Source

pub async fn run_concurrent(self) -> Result<(), BoxError>

Available on crate feature concurrency-tokio only.

Start the runtime and begin polling for events on the Lambda Runtime API, in a mode that is compatible with Lambda Managed Instances.

When AWS_LAMBDA_MAX_CONCURRENCY is set to a value greater than 1, this spawns multiple tokio worker tasks to handle concurrent invocations. When the environment variable is unset or <= 1, it falls back to sequential behavior, so the same handler can run on both classic Lambda and Lambda Managed Instances.

§Panics

This function panics if called outside of a Tokio runtime.

Source§

impl<S> Runtime<S>
where S: Service<LambdaInvocation, Response = (), Error = BoxError>,

Source

pub async fn run(self) -> Result<(), BoxError>

Start the runtime and begin polling for events on the Lambda Runtime API.

The runtime will process requests sequentially.

§Managed concurrency

If AWS_LAMBDA_MAX_CONCURRENCY is set, a warning is logged. If your handler can satisfy Clone + Send + 'static, prefer Runtime::run_concurrent (requires the concurrency-tokio feature), which honors managed concurrency and falls back to sequential behavior when unset.

Auto Trait Implementations§

§

impl<S> !RefUnwindSafe for Runtime<S>

§

impl<S> !UnwindSafe for Runtime<S>

§

impl<S> Freeze for Runtime<S>
where S: Freeze,

§

impl<S> Send for Runtime<S>
where S: Send,

§

impl<S> Sync for Runtime<S>
where S: Sync,

§

impl<S> Unpin for Runtime<S>
where S: Unpin,

§

impl<S> UnsafeUnpin for Runtime<S>
where S: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more